C - 印刷中的双精度50个有效数字产生不准确的值 [英] Double precision in C - printing 50 significant figures yields inaccurate values

查看:118
本文介绍了C - 印刷中的双精度50个有效数字产生不准确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在和我的微积分类Riemann总和做一个整合程序。我决定在计算我的积分时使用C,我发现我的程序中出现了一个巨大的错误,这个错误来源于这个问题。

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

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

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


return(EXIT_SUCCESS);
}

该程序给了我:0.10000000000000000555111512312578270211815834045410。我的问题:为什么会发生这种情况?我该怎么解决这个问题?或至少舍入〜15位小数位数?



感谢您的帮助。

解决方案

浮点数的基础:



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



您的案例中的答案 0.10 不能在二进制浮点数中表示。因此,只有16位数字才能正确。但是,您尝试将其打印到50位小数位。


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.

解决方案

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.

这篇关于C - 印刷中的双精度50个有效数字产生不准确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆