Double precision in C - printing 50 significant figures yields inaccurate values

删除回忆录丶 提交于 2019-12-21 19:57:01

问题


I'm doing an integration program with Riemann sums for my Calculus class. I've decided to use C when computing my integrals, and I noticed a huge error in my program that derives from this problem.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char** argv) {

double x = 2.0/20.0;
printf("%1.50f \n", x);


return (EXIT_SUCCESS);
}    

The program gives me : 0.10000000000000000555111512312578270211815834045410. My question: Why does this happen? And how can I fix this? Or at least round off to ~15 decimal places?

Thanks for the help.


回答1:


The basics of floating-point:

http://en.wikipedia.org/wiki/Floating_point

The answer in your case 0.10 is not exactly representable in binary floating-point. Therefore, it's only accurate to about 16 digits. Yet you are trying to print it out to 50 decimal places.




回答2:


If you need more accurate results that what double can offer, then you may want to check out some of the arbitrary precision libraries that are available.



来源:https://stackoverflow.com/questions/7816504/double-precision-in-c-printing-50-significant-figures-yields-inaccurate-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!