std.complex

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue May 11 05:52:46 PDT 2010


On Tue, 11 May 2010 11:51:34 +0000, eles wrote:

> the following test case also works:
> 
> Compiling
> 
> import std.stdio;
> import std.complex;
> 
> Complex!(double) x,y;
> 
> int main(){
> 	writefln("salut!\n");
> 	x.re=1;
> 	x.im=1;
> 	y=x.conj();
> 	writefln("x=%f+%f*i\n",x.re,x.im);
> 	writefln("y=%f+%f*i\n",y.re,y.im);
> 	return 0;
> }
> 
> 
> results in
> 
> C:\dmd2>dmd test.d
> 
> C:\dmd2>test
> salut!
> 
> x=1.000000+1.000000*i
> 
> y=1.000000+-1.000000*i
> 
> C:\dmd2>

Cool!


> Which is OK. However, displaying complex numbers in that way is not very
> nice. Is there any dedicated formatting for that? (it would be nice to
> be able displaying a complex number in both Cartesian and Polar formats)

The problem is that there doesn't seem to be any "standard" way of 
converting stuff to strings in Phobos.

The toString() function I put into Complex is designed to write complex 
numbers to an arbitrary output range.  It may seem very verbose when all 
you want to do is to get a simple string representation, but it was meant 
as a proposal for exactly such a standard.

Another possibility was proposed by Don, as demonstrated in 
std.bigint.BigInt.toString():

    http://www.digitalmars.com/d/2.0/phobos/std_bigint.html#toString

The idea is that if a type defines such a toString(), it should -- in the 
future, that is -- work automatically with std.conv.to(), 
std.stdio.writef*() etc.  Then you'd be able to do things like

    auto z = Complex!real(1, -2);

    auto str1 = to!string(z);
    assert (str1 == "1-2i");

    writefln("%.2g", z); // Prints "1.00-2.00i"

Right now, you are kind of stuck with the way you demonstrated, or you 
can have Complex.toString() write to an std.array.Appender!string range.

-Lars


More information about the Digitalmars-d-learn mailing list