gpt4 book ai didi

c++ - 浮点运算 : why would order of addition matter?

转载 作者:太空狗 更新时间:2023-10-29 20:01:57 25 4
gpt4 key购买 nike

我知道用有限的位数不可能以任意精度表示所有数字,并且不建议对 float 进行简单的比较。但我希望,如果我将许多数字加在一起,我添加它们的 ** 顺序 ** 并不重要。

为了测试这个预测,我创建了一个随机数 vector 并计算它们的总和,然后对 vector 进行排序并再次计算总和。很多时候,这两个总和不匹配!这是我的代码(包括在下面)的问题、一般浮点运算的缺点,还是可以通过切换编译器等解决的问题?

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>

double check_sum_depends_on_order(int seed)
{
// fill a vector with random numbers
std::vector<long double> v;
std::uniform_real_distribution<long double> unif(-1.,1.);
std::mt19937 rng(seed);
for (size_t i = 0; i < 1000; ++i)
{
v.push_back(unif(rng));
}

// copy this vector and then shuffle it
std::vector<long double> v2 = v;
std::sort(v2.begin(), v2.end());


// tot is running total for vector v, unsorted
// tot2 is running total for vector v2, sorted
long double tot = 0.0, tot2 = 0.0;
for (size_t i = 0; i < v.size(); ++i)
{
tot += v[i];
tot2 += v2[i];
}

// display result
// you can comment this if you do not want verbose output
printf("v tot\t= %.64Lf\n", tot);
printf("v2 tot\t= %.64Lf\n", tot2);
printf("Do the sums match (0/1)? %d\n\n", tot==tot2);

// return 1.0 if the sums match, and 0.0 if they do not match
return double(tot==tot2);
}

int main()
{
// number of trials
size_t N = 1000;

// running total of number of matches
double match = 0.;
for (size_t i = 0; i < N; ++i)
{
// seed for random number generation
int seed = time(NULL)*i;
match += check_sum_depends_on_order(seed);
}

printf("%f percent of random samples have matching sums after sorting.", match/double(N)*100.);
return 0;
}

最佳答案

假设您有一个精度为三位的十进制浮点类型。不太现实,但它提供了一个更简单的示例。

假设您有三个变量,abc。假设a1000bc都是14

a + b 将是 1014,四舍五入为 1010。(a + b) + c 将是 1024,四舍五入为 1020。

b + c 将是 28。a + (b + c) 将是 1028,四舍五入为 1030。

关于c++ - 浮点运算 : why would order of addition matter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957828/

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