0

The answer is off by 2.84217e-014 when trying to rake 5 root of a big number

#include <iostream>
#include <math.h> 
using namespace std;   

int main(){
    //144^5 = 61917364224
    cout << fmod(pow(61917364224, 1/5.0), 1) << endl; // 2.84217e-014
}
  • 3
    Floating-point numbers are not infinitely precise, it is expected that round-off errors occur. – Jesper Oct 07 '20 at 13:25
  • 3
    "The answer is off by 2.84217e-014 when trying to rake 5 root of a big number" which ain't bad really. That's off on the order of centimetres on the distance from here to Neptune. If you want to do better than that then use a multiprecision library. – Bathsheba Oct 07 '20 at 13:27
  • 1
    probably an x-y problem. OP, why are you needing the 5th root of an integer value? Are you trying to solve a problem on integers? Then floating point is not the right tool – Jeffrey Oct 07 '20 at 13:29
  • `pow(x,y)` is typically computed as `exp(y*log(x)`, with some precision enhancements (see for instance in [glibc](https://github.com/lattera/glibc/blob/master/sysdeps/ieee754/dbl-64/e_pow.c)). It's not an exact computation. –  Oct 07 '20 at 13:33
  • If you need a integer-only solution for calculating roots this can easily be done: https://gcc.godbolt.org/z/Yscos3 – Simon Kraemer Oct 07 '20 at 13:43
  • 1
    @SimonKraemer Incrementing by one at each step if vastly suboptimal. For instance there is a well known algorithm for integer square root that first computes the higest bit, then all subsequent bits, one per loop. There is also Newton's method. –  Oct 07 '20 at 13:46
  • @Jean-ClaudeArbaut the compiler does a pretty good job optimizing the code (constexpr FTW). It wasn't meant to show a perfect solution, just that there are other methods available. – Simon Kraemer Oct 07 '20 at 13:51

0 Answers0