How to find the root of a negative integer cube so that it does not return NaN?

In Haskell, I tried to find the cube root of a negative integer, like -1, without success.

I used (-1) ** (1/3), but that returns NaN. I thought it may have something to do with the type (1/3) fraction, but the use of (1/3 :: Double) also did not bring success.

As a result, my question is how to find the cube root of -1 with Haskell so that it does not return NaN?

+4
source share
3 answers

Haskell (**) (), ( ) . , , C pow :

printf("%f\n", pow(-1.0, 1.0/3.0));   // prints "-nan", for me

Python **:

print((-1.0)**(1.0/3.0)) 
# gives: ValueError: negative number cannot be raised to fractional power

. " " . . , SO.

, , , , @Istvan signum sign, :

cbrt x = signum x * abs x ** (1/3)

, , n n- , , , :

-- | Calculate nth root of b
root :: (Integral n, RealFloat b) => n -> b -> b
root n b | odd n && b < 0  = - abs b ** overn
         | otherwise       = b ** overn
    where overn = 1 / fromIntegral n

:

> root 3 (-8)
-2.0
> root 4 (-8)
NaN      -- correct, as no real root exists
>
+5

Haskell, - : (x) * abs (x) ** (1/3)

+1

On ghci, I did what seems to solve your problem:

let cbrt x = if x < 0 then -((-x) ** (1/3)) else x ** (1/3)

A simple function Coubertin.

Since I'm still involved, I do not know whether this is the right decision, so please let me know if something is wrong or not;)

+1
source

Source: https://habr.com/ru/post/1685825/


All Articles