如何提高结果的精度由于C ++划分的缺乏精度 [英] How to improve the precision of the result due to the lack of precision in C++ division

查看:124
本文介绍了如何提高结果的精度由于C ++划分的缺乏精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理指示的leibniz问题 https://www.hackerrank.com/challenges/leibniz 这里。
其计算1-1 / 3 + 1 / 5-1 / 7 + 1/9 + ...序列中的每个元素可以被定义为a(i)=( - 1)^ i / * i + 1)从0开始i。



问题要求从第一项添加到第n项,并输出结果。我的程序通过了基本的测试用例。但它在其他情况下失败。



我猜我的程序错误是由于数字足够大时的精度。



任何人都可以提供一种方法来提高结果的精确度。

  double leibnitz(int n){
double res = 0.0;
for(int i = 1; i <= n; i ++){
res + = 1.0 /(2 * i-1)*(i%2 ==1≤1.0: ;
}
return res;
}


解决方案



原因是可以以更高的精度添加大约0的小数字,因为前导零将是表示在浮点数的指数部分(因此名称为浮点),使更多的尾数可用。因此,您可以使用更精确的小部分之和接近1.



循环应如下所示:

  for(int i = n; i> = 1; i--){
res + = 1.0 /(2 * i-1)* i%2 == 1?1.0:-1.0);
}

Jsfiddle有一个更简单的问题来说明顺序可能会有所不同: / p>

http://jsfiddle.net/smt56/1



BTW:您应该可以将表达式缩短到

  res + =((i%2)* 2-1)/(2.0 * i-1)


I am working on the leibniz question as indicated https://www.hackerrank.com/challenges/leibniz here. which computes 1-1/3+1/5-1/7+1/9+... Each element in the sequence can be defined as a(i)=(-1)^i/(2*i+1) start i from 0.

The question requires that to add from the first term to the nth term and output the result. My program passes the basic test cases. But it fails in other cases.

I guess my program fault is due to the precision when the number is large enough.

Can anybody provide a way to improve the precision of the result?

double leibnitz(int n) {
    double res = 0.0;
    for (int i = 1; i <= n; i++) {
        res += 1.0 / (2 * i - 1) * (i % 2 == 1 ? 1.0 : -1.0);
    }
    return res;
}

解决方案

Start the loop with n and count down.

The reason is that small numbers around 0 can be added with higher precision because leading zeroes will be represented in the exponent part of the floating point number (hence the name "floating point"), making more of the mantissa available. So you may be able to approach 1 with a more precise sum of the smaller parts.

The loop should look like this:

for (int i = n; i >= 1; i--) {
    res += 1.0 / (2 * i - 1) * (i % 2 == 1 ? 1.0 : -1.0);
}

Jsfiddle with a simpler problem to illustrate that ordering may make a difference here:

http://jsfiddle.net/smt56/1

BTW: You should be able to shorten the expression to

res += ((i % 2) * 2 - 1) / (2.0 * i - 1)

这篇关于如何提高结果的精度由于C ++划分的缺乏精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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