双舍入误差 [英] double rounding error

查看:118
本文介绍了双舍入误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用两个带变量a,b和c的函数,每个函数都是double。功能如下:



(a-32)(5/9)+273.15 = b和(b-273.15)(9/5)+32 = c这些函数为a的所有值赋予a = c属性。



大部分工作正常,但是如果a = 0我得到c = 1.06e-14。



这是一个非常小的数字所以它不会是一个问题,但是值a和c都被转换为字符串并显示在UILabels上,id使用以下代码执行此操作,_Value2.text是我的UILabel上显示的文本:



_Value2.text = [NSString stringWithFormat:@%。7g ,c];



当a = 0,_Value2.text = @1.06e-14这是一个问题,它只发生在a = 0时br />


我假设这个错误来自编译器中的舍入错误但是如何修复/避免这个问题?

I am using two functions with variables a,b, and c with each being a double. the functions are as follows:

(a-32)(5/9)+273.15 = b and (b-273.15)(9/5)+32 = c these functions give the property that a = c for all values of a.

for the most part it is working fine, however if a = 0 i get c = 1.06e-14.

this is a really small number so it wouldn't be a problem however both values a and c are being converted to strings and displayed on UILabels, id do this with the following code with _Value2.text being the text shown on my UILabel:

_Value2.text = [NSString stringWithFormat:@"%.7g", c];

when a = 0, _Value2.text = @"1.06e-14" this is a problem and it only occurs when a = 0.

I am assuming this error is from a rounding error in the compiler but how can I fix/avoid this issue?

推荐答案

这种舍入问题在浮点运算中很常见。



在你的情况下你是ma你只需要检查小数字并在打印前指定零:

Such rounding problems are common with floating point operations.

In your case you may just check for small numbers and assign zero before printing:
if (fabs(c) <= 1e-8)
    c = 0.0;





您遇到此问题,因为您使用的是'%g'格式。你的配方是某种温度转换/计算。无需打印比数值精度更多的数字。因此,根据输入值的范围和准确性,您可以将格式更改为'%。3f'。您也可以使用固定宽度:'%8.3f'将打印小于千位的aboslute值,小数点后面有三位数。



You have this problem because you are using the '%g' format. Your formula is some kind of temperature conversion/calculation. There is no need to print more digits than the precision of your values. So you may change your format to something like '%.3f' depending on the range and accuracy of the input values. You may also use a fixed width: '%8.3f' will print aboslute values less than thousand with three digits after the decimal point.


这篇关于双舍入误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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