Search code examples
dexponentiationreal-datatype

Exponentiation of negative real


Can somebody explain why I'm getting a positive result in the first case and a negative in the second.

auto r1 = -3.0L;
auto r2 = 2.0L;
writeln(typeid(r1)); // real 
writeln(typeid(r2)); // real 
writeln(typeid(r1 ^^ r2)); // real
writeln(r1 ^^ r2); // 9

writeln(typeid(-3.0L)); // real
writeln(typeid(2.0L)); // real
writeln(typeid(-3.0L ^^ 2.0L)); // real
writeln(-3.0L ^^ 2.0L);  // -9

Solution

  • Disclaimer: I don't know D. This is written with my background using other languages.

    When you square a negitive (real) number, the number becomes positive. You are writing the ambiguous (to humans) expression:

    -3^2
    

    Which could mean either:

    • -(3^2) = -9 or
    • (-3)^2 = 9

    Judging from the output, I assume that the programming language's operator precedence is picking the first. Try replacing your last line with:

    writeln((-3.0L) ^^ 2.0L);  // -9