digitalmars.D.learn - Complex number syntax
- bearophile (42/42) Nov 11 2007 I don't seem to understand/like D complex number syntax. This little tes...
- Jarrett Billingsley (5/6) Nov 11 2007 You almost had it there, use
-
Stewart Gordon
(13/20)
Nov 12 2007
"bearophile"
wrote in message
I don't seem to understand/like D complex number syntax. This little test program shows complex numbers usage with a struct, and then I have tried to do the same with the built-in complex reals, and I have failed. Can you help me? And can the D complex number sintax be made more user-friendly? :-) The first line also shows yet another problem of writefln, it prints: 2-5i as 2+-5i import std.stdio, std.string; void main() { writefln("neg im: ", 2-5i); // Prints: neg im: 2+-5i struct Complex { real re, im; string toString() { if (im >= 0) return format(re) ~ '+' ~ format(im) ~ 'i'; else return format(re) ~ format(im) ~ 'i'; } } Complex[8] data1; foreach(int n, ref d; data1) { d.re = -n-5; d.im = n-5; } writefln(data1); // Prints: // [-5-5i,-6-4i,-7-3i,-8-2i,-9-1i,-10+0i,-11+1i,-12+2i] cfloat[8] data2; foreach(int n, ref d; data2) { // d.re = -n-5; // not possible? // d.im = n-5; // not possible? // d = (-n-5, n-5); // not possible // d = -n-5 + (n-5) i; // not possible // d = cast(cfloat)(-n-5, n-5); // not possible d = cast(float)(-n-5) + cast(ifloat)(n-5); } writefln(data2); // Prints: // [-5+0i,-6+0i,-7+0i,-8+0i,-9+0i,-10+0i,-11+0i,-12+0i] } Bye and thank you, bearophile
Nov 11 2007
"bearophile" <bearophileHUGS lycos.com> wrote in message news:fh77bs$295e$1 digitalmars.com...// d = -n-5 + (n-5) i; // not possibleYou almost had it there, use d = (-n - 5) + (n - 5) * 1i; and it works.
Nov 11 2007
"bearophile" <bearophileHUGS lycos.com> wrote in message news:fh77bs$295e$1 digitalmars.com... <snip>cfloat[8] data2; foreach(int n, ref d; data2) { // d.re = -n-5; // not possible? // d.im = n-5; // not possible?These ought to work.// d = (-n-5, n-5); // not possibleBecause (-n-5, n-5) is a comma expression. It evaluates -n-5, and then evaulates and returns n-5.// d = -n-5 + (n-5) i; // not possibleBecause i isn't a keyword, it's a literal suffix.// d = cast(cfloat)(-n-5, n-5); // not possible<snip> See above. Stewart. -- My e-mail address is valid but not my primary mailbox. Please keep replies on the 'group where everybody may benefit.
Nov 12 2007