Chaabane_Mankai's blog

By Chaabane_Mankai, 6 weeks ago, In English

I have been lately working on a problem and I have noticed that pow() function gives me sometimes a wrong number. $$$\newline$$$ Here's an example : $$$\newline$$$ I wanted to calculate $$$3^{38}$$$ : The calculator indicates that it is equal to 1350851717672992089. However, when I executed the command pow(3,38); I got this number instead : 1350851717672992000. $$$\newline$$$ Can anyone explain to me why is this happening and how to fix it ?

 
 
 
 
  • Vote: I like it
  • -7
  • Vote: I do not like it

»
6 weeks ago, # |
  Vote: I like it +13 Vote: I do not like it

The core algorithm for pow(x, y) computes a logarithm from (a part of) x, multiplies it by y, and computes an exponential function on the product. By using above algorithm floating point induces errors which results in diversion. Therefore it is generally recommended to create power function when in use or save it in your template

»
6 weeks ago, # |
Rev. 2   Vote: I like it +14 Vote: I do not like it

Doubles can exactly represent all integers between $$$-2^{52}$$$ and $$$2^{52}$$$. But for example $$$2^{52} + 1$$$ can not be stored in a double. $$$3^{38} > 2^{52}$$$, so it is unlikely $$$3^{38}$$$ has an exact representation.

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Use Binary Exponentiation Binary_Expo

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

no

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

So is there any way to improve the accuracy of pow, Binary_Expo is a bit of a pain.