Question

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
Was it helpful?

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

OTHER TIPS

There is nothing wrong in the source above. Even good, old FORTRAN has power operator with the highest precedence (see http://h21007.www2.hp.com/portal/download/files/unprot/fortran/docs/lrm/lrm0067.htm for an example). Thus, in almost every modern programming language that has the power operator, expression -3^2 will be evaluated as -(3^2).

This rule is the same even in mathematical expressions: http://en.wikipedia.org/wiki/Order_of_operations#Exceptions_to_the_standard

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top