2

So, when I try to calculate this operation, I get a NaN result.

double raz3 = pow(-64, 1.0/3);

It should return -4, but it returns -NaN instead. I have thought that it was an overflow problem, so I changed the type to long long, instead I receive a value of -9223372036854775808

How can I make it return -4?

prepz
  • 21
  • 2
  • 2
    From [cppreference](https://en.cppreference.com/w/cpp/numeric/math/pow) : If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur. – François Andrieux Oct 21 '19 at 14:55
  • 2
    `1/3` can't be perfectly represented in binary system, same way as it can't be represented in decimal system. Can you tell me what is the result of: `(-64)^0.333333`? – Marek R Oct 21 '19 at 14:56
  • @MarekR `0.333333` is also not perfectly represented by a `double`. – François Andrieux Oct 21 '19 at 14:57
  • @FrançoisAndrieux this is just an example showing the problem in human readable form. – Marek R Oct 21 '19 at 14:58
  • 3
    TL;DR: Use [`std::cbrt`](https://en.cppreference.com/w/cpp/numeric/math/cbrt). Note that this still uses floating point math; there is no standard function that extracts the cube roots of integers for perfect cubes (because it would have to be undefined for almost all its inputs). – Max Langhof Oct 21 '19 at 14:58
  • @MaxLanghof I cannot use a "static" root function. The full code would be ```double raz1 = uv / pv; double raz2 = vp - 1; double raz3 = pow(raz1, 1.0/raz2); ``` The values are inputs from the user, the function works fine, but fails with these values. Is there any way of fixing it? – prepz Oct 21 '19 at 15:11
  • @prepz I gave you the shortest answer that fixes your code, but the dupe has other, more general ways (which boil down to removing the sign beforehand and re-applying it afterwards - which would have to happen behind the scenes anyway). – Max Langhof Oct 21 '19 at 15:17

0 Answers0