lua-users home
lua-l archive

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

2016-04-14 12:30 GMT+02:00 Christopher Kappe <>:
> 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

No, it stems from the fact that math.pow cannot know that 1/3 is
a rational number. It cannot even know that 0.5 is a rational number
and not the floating-point approximation to an irrational number.

The best solution to this is to write a

 (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.