3

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
5
  • 2
    I'm no expert, but I think the negative is added after the exponent. Wrap -3.0L in parenthesis
    – Cole Tobin
    May 21, 2012 at 5:28
  • @Cole You mean it's an operator precedence issue? Adding parens does make a difference.
    – fwend
    May 21, 2012 at 5:33
  • as I said. Idk. I don't progrAm in d
    – Cole Tobin
    May 21, 2012 at 5:35
  • I think it's the correct answer, ^^ is left associative in D. I didn't think of that.
    – fwend
    May 21, 2012 at 5:39
  • 1
    @fwend: This isn't a result of associativity. If ^^ were right associatitve, you would get the same result. This is purely a precedence issue. May 21, 2012 at 9:20

2 Answers 2

5

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
2
  • 2
    That's not really ambiguous, actually. In both math and programming languages it is clearly defined.
    – Joey
    May 21, 2012 at 6:04
  • 2
    @Joey As is the case with all operators when you combine them in an expression, it would be ambiguous were there no operator precedence, but naturally, that's why operator precedence is there. It makes the expression unambiguous to the compiler. However, it can clearly still be confusing to the programmer if they don't know the precedence of the operators involved. May 21, 2012 at 20:49
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.