Function calculation error

I have this function, which is simply a sum and a product. For some values, work for others does not in the sense not return the correct result.

Codia function (r, c) { return ((r + c) * (r + c + 1)); } alert(Codia(1908229752,0)); 

The result obtained by the function: 3641340788326211000

The result calculated by me: 3641340788326211256

Can you tell me where I am going wrong.

+6
source share
1 answer

JavaScript is not designed to be accurate. When you have floats and doubles or numbers greater than Number.MAX_SAFE_INTEGER (this is 9007199254740991), the numbers will begin to lose their accuracy. Here you can compare your expected answer and the maximum safe integer:

 3,641,340,788,326,211,256 EXPECTED ANSWER 9,007,199,254,740,991 MAX_SAFE_INTEGER 

To fix this, use a library designed to create arithmetic with large numbers, or develop a new algorithm yourself.

Here is an example of using BigNumber.js that returns the correct answer 3641340788326211256: http://jsfiddle.net/DerekL/jj47touj/

+4
source

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


All Articles