Complex number syntax

bearophile bearophileHUGS at lycos.com
Sun Nov 11 07:33:16 PST 2007


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


More information about the Digitalmars-d-learn mailing list