Search code examples
rubybigdecimal

Some BigDecimal fail to calculate with ** operator


When I use ** operator with negative BigDecimal and decimal BigDecimal, that fails with Zero or negative argument error.

I checked some similar values like this:

-2 ** '0.3'.to_d
# => -1.23114441
2 ** '0.3'.to_d
# => 1.23114441
2 ** '0.3'.to_d
# => 1.23114441
-2 ** '0.3'.to_d
# => -1.23114441
2.to_d ** '0.3'.to_d
# => 1.23114441
-2.to_d ** '0.3'.to_d
# => Math::DomainError: Zero or negative argument for log
from (pry):111:in `**'
2.to_d ** 3.to_d
# => 8.0
-2.to_d ** 3.to_d
# => -8.0

Why is this error happens and how can I fix it?


Solution

  • I understand now what I have misunderstood.

    I thought -2.0 ** 0.3 is same as (-2.0) ** 0.3, but it is same as -(2.0 ** 0.3).

    I didn't know that ** is stronger than -.