gpt4 book ai didi

c++ - 再次 double 四舍五入

转载 作者:行者123 更新时间:2023-11-28 05:52:01 30 4
gpt4 key购买 nike

在我的程序中有一些精度(一些正整数,在大多数情况下它应该是 x*10^n 的形式)用于一些 double ,所以 double * precision 应该变成一个整数.

但众所周知, float 是不准确的,因此,例如 1.3029515 可以保存为 1.3029514999999998...,在我的程序中我需要编写这样的 float 到一个文件,但我想写这个 1.3029515 而不是像 1.3029514999999998... 这样的东西。

以前只有形式的精度 10^n, 0<=n<=8在我的程序中使用了,我用如下一段代码达到了想要的结果:

// I have a function for doubles equality check
inline bool sameDoubles(const double& lhs, const double& rhs, const double& epsilon) {
return fabs(lhs - rhs) < epsilon;
}

inline void roundDownDouble(double& value, const unsigned int& numberOfDigitsInFraction = 6) {
assert(numberOfDigitsInFraction <= 9);
double factor = pow(10.0, numberOfDigitsInFraction);
double oldValue = value;
value = (((int)(value * factor)) / factor);
// when, for example, 1.45 is stored as 1.4499999999..., we can get wrong value, so, need to do the check below
double diff = pow(10.0, 0.0 - numberOfDigitsInFraction);
if(sameDoubles(diff, fabs(oldValue - value), 1e-9)) {
value += diff;
}
};

但是现在,我无法用同样的技术达到想要的结果,我尝试了下面的函数,但没有成功:

// calculates logarithm of number with given base
double inline logNbase(double number, double base) {
return log(number)/log(base);
}

// sameDoubles function is the same as in above case

inline void roundDownDouble(double& value, unsigned int precision = 1e+6) {
if(sameDoubles(value, 0.0)) { value = 0; return; }
double oldValue = value;
value = ((long int)(value * precision) / (double)precision);
// when, for example, 1.45 is stored as 1.4499999999..., we can get wrong value, so, need to do the check below
int pwr = (int)(logNbase((double)precision, 10.0));
long int coeff = precision / pow(10, pwr);
double diff = coeff * pow(10, -pwr);
if(sameDoubles(diff, fabs(oldValue - value), diff / 10.0)) {
if(value > 0.0) {
value += diff;
} else {
value -= diff;
}
}
}

对于 1.3029515 值和 precision = 2000000 此函数返回不正确的 1.302951 值(表达式 (long int)(value * precision ) 等于 2605902 而不是 2605903)。

我该如何解决这个问题?或者也许有一些聪明的方法可以正确地进行舍入?

最佳答案

您正在以艰难的方式四舍五入。改用简单的方法:

double rounding = 0.5;
if (value < 0.0) rounding = -0.5;
value = ((long int)(value * precision + rounding) / (double)precision);

现在不需要剩下的代码了。

关于c++ - 再次 double 四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040815/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com