lua-users home
lua-l archive

compute cubic root with negative argument

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,
I just noticed that it is not possible to compute the cubic root of a negative number. See e.g.
print( math.pow( -27, 1/3 ) ) --> -nan instead of -3
The same is true for the ^ operator (not surprising).
This probably stems from the fact that the result of the n-th root of a negative number is not real if n is even (e.g. sqrt(-1) = (-1)^(1/2) = i). However, (-3)^3 = -27 and likewise should hold that (-27)^(1/3) = -3. This works by the way with Google (try googling f(x) = x^(1/3) and you will see the graph of the function also for the negative x-axis). If such a correct behavior is not easy to implement in the generic math.pow function, I would suggest offering a math.cbrt function as exists e.g. in C, C++ or Octave. The least one should do, is document the fact that exponentiation only works for a non-negative base argument.
Regards,
Christopher

AltStyle によって変換されたページ (->オリジナル) /