std :: pow与整数参数,比较一个整数类型 [英] std::pow with integer parameters, comparing to an integer type

查看:251
本文介绍了std :: pow与整数参数,比较一个整数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://en.cppreference.com/w/cpp/当使用整数参数 std :: pow 时,结果被提升为 double

我的问题是这样的:

安全性是比较一个整型结果是一个 std :: pow(int1,int2)
例如,如果 if 下面的计算结果为true?

  std :: size_t n = 1024; 
if(n!= std :: pow(2,10))
cout<< 舍入问题...<< ENDL;

也就是说,rhs上的结果可能类似于1023.99 ... 9所以当转换成size_t成为1023?

我的猜测是在一个很大的答复,但想知道肯定。我在检查矩阵的维数时使用了这种比较,我不想在任何地方使用 std :: round

这很有趣,你应该问,因为 pow 不能计算在他们的平台上有明显的结果(另见我的 pow 时,对小整数来说,参数和理想的数学结果都是完全可以表示的。这不会强制执行 exp 来返回数学结果,因为没有标准指定 pow 不能被不准确不止一个 ULP 。至少有一个非常流行的平台默认提供了一个不会计算 pow(10,2)的函数 pow 100,但是你可以随意使用 pow(2,N)来获得机会,也许它总会返回你有权期望的整数。


According to http://en.cppreference.com/w/cpp/numeric/math/pow , when std::pow is used with integer parameters, the result is promoted to a double.

My question is then the following:

How safe is to compare an integer type with the result of a std::pow(int1, int2)? For example, can the if below evaluate to true?

std::size_t n = 1024;
if(n != std::pow(2, 10))
    cout << "Roundoff issues..." << endl;

That is, is it possible that the result on the rhs can be something like 1023.99...9 so when converted to size_t becomes 1023?

My guess is that the response in a big NO, but would like to know for sure. I am using these kind of comparisons when checking for dimensions of matrices etc, and I wouldn't like to use a std::round everywhere.

解决方案

It is funny you should ask, because someone else on StackOverflow had a question that was caused by the very fact that pow applied to small integers did not compute the obvious result on their platform (see also my writeup).

So yes, when applying pow to small integers, both arguments and ideal mathematical result are exactly representable. This does not force the implementation of exp to return the mathematical result, because no standard specifies that pow cannot be inaccurate by more than one ULP. And at least one very popular platform provides by default a pow function that does not compute pow(10, 2) as 100, but you are free to take you chances with pow(2, N) and perhaps it will happen to always return the integer you are entitled to expect.

这篇关于std :: pow与整数参数,比较一个整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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