gpt4 book ai didi

c++ - 为什么 c++ double 会将自己限制为小数点后 5 位?

转载 作者:太空狗 更新时间:2023-10-29 19:39:25 24 4
gpt4 key购买 nike

我希望你能帮上点忙。

我写了一个模板类来计算标准偏差:

template <class T>
double GetStandardDeviation(T* valueArray, int populationSize)
{
double average;
T cumulativeValue = 0;
double cumulativeSquaredDeviation = 0;
// calculate average
for (int i = 0; i < populationSize; i++)
{
cumulativeValue += valueArray[i];
}
average = (double)cumulativeValue / (double)populationSize;
// calculate S.D.
for (int i = 0; i < populationSize; i++)
{
double difference = average - (double)valueArray[i];
double squaredDifference = difference * difference;
cumulativeSquaredDeviation += squaredDifference;
}
return cumulativeSquaredDeviation / (double)populationSize;

}

这似乎一切都正确,只是它返回的结果只保留了小数点后 5 位。任何人都可以提出一个原因吗?我很难过!

最佳答案

IEEE-754 double 值具有大约 15 位小数的精度,因此只有当您的值达到数百亿左右时,它才会被限制为小数点后五位。

您最有可能看到的只是 double 的默认输出格式,与 C 一样,它往往会为您提供有限数量的小数位。

您可以在以下代码中看到这一点:

#include <iostream>
#include <iomanip>
int main(void) {
double d = 1.23456789012345;
std::cout << d << '\n';
std::cout << std::setprecision(16) << d << '\n';
return 0;
}

其输出为:

1.23457
1.23456789012345

C++03 标准中的表 89(在 27.4.4.1 basic_ios 构造函数中)显示了调用 basic_ios::init() 后的后置条件,它显示默认精度为 6。在 C++11 中,它表示相同的内容,仅在 27.5.5.2 basic_ios constructors 下的表 128 中。

关于c++ - 为什么 c++ double 会将自己限制为小数点后 5 位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18828135/

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