第一篇文章!
我为数值模拟编写的程序有问题,乘法有问题。基本上,我试图计算:
result1 = (a + b)*c
这会循环数千次。我需要将此代码扩展为
result2 = a*c + b*c
但是,当我这样做时,我的结果开始出现重大错误。我使用了一个高精度库,它确实改进了一些东西,但是模拟运行速度非常慢(模拟花费了 50 倍的时间),而且它确实不是一个实用的解决方案。由此我意识到,真正伤害我的并不是变量 a、b 和 c 的精度,而是乘法完成的方式。
我的问题是:我怎样才能将这些括号乘以结果1 = 结果2?
谢谢。
解决了!!!!!!!!!
这是添加的问题。因此,我通过编写以下代码对术语进行了重新排序并应用了 Kahan 加法:
double Modelsimple::sum(double a, double b, double c, double d) {
//reorder the variables in order from smallest to greatest
double tempone = (a<b?a:b);
double temptwo = (c<d?c:d);
double tempthree = (a>b?a:b);
double tempfour = (c>d?c:d);
double one = (tempone<temptwo?tempone:temptwo);
double four = (tempthree>tempfour?tempthree:tempfour);
double tempfive = (tempone>temptwo?tempone:temptwo);
double tempsix = (tempthree<tempfour?tempthree:tempfour);
double two = (tempfive<tempsix?tempfive:tempsix);
double three = (tempfive>tempsix?tempfive:tempsix);
//kahan addition
double total = one;
double tempsum = one + two;
double error = (tempsum - one) - two;
total = tempsum;
// first iteration complete
double tempadd = three - error;
tempsum = total + tempadd;
error = (tempsum - total) - tempadd;
total = tempsum;
//second iteration complete
tempadd = four - error;
total += tempadd;
return total;
}
这给了我与精确答案一样接近的结果,没有区别。然而,在一个矿井坍塌的虚构模拟中,添加 Kahan 的代码需要 2 分钟,而高精度库需要一天才能完成!
感谢这里的所有帮助。这个问题真是让人头疼。