Exponentiality of negative real

Can someone explain why I get a positive result in the first case and 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
+3
source share
2 answers

Disclaimer: I do not know D. This is written by my background using other languages.

By squaring a negative (real) number, the number becomes positive. You write an ambiguous expression (for people):

-3^2

This could mean either:

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

Judging by the conclusions, I assume that the first chooses the priority of the programming language operator. Try replacing the last line:

writeln((-3.0L) ^^ 2.0L);  // -9
+5
source

All Articles