dawud's blog

By dawud, history, 3 years ago, In English

Hi, Recently while practicing I found this problem, Please run this code in your local machine.

Code

If you run this code you should see something like this

Output

Your can also see this code running in IDEONE
You can see there from i = 16 , the program is giving wrong output.
There should be all 1s in every number.
Can anyone please tell me

  • Why this is giving wrong result even in this small range ?
  • And how to avoid this type of calculation problem ?

Thanks in advance ❤️❤️❤️

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

»
3 years ago, # |
  Vote: I like it +1 Vote: I do not like it

In double, if you calculate a sufficiently large number, you will round a very small number, which will result in an error. Compared to double, long double has a much smaller error, so some topics that require more precision may consider using long double.

If you want a really accurate solution, consider using an array to hold each number.

  • »
    »
    3 years ago, # ^ |
    Rev. 2   Vote: I like it +3 Vote: I do not like it

    I would advise strongly against using floating-point (i.e. double/long double) numbers in any solution where there is no allowance for small errors. Even long double doesn't have a much bigger guaranteed precision range for integers (I believe it's around $$$2^{64}$$$ vs $$$2^{53}$$$).

    Keep in mind that of course there are exceptions when you know you won't be dealing with such large numbers but are using non-integers in intermediate calculations. Still, it is hard to be sure that there will be no rounding error.