问题描述
我正在做一些数学运算,我刚发现标准库
没有提供标准的PI值。在较老的帖子中我看到每个人都说
你必须自己定义它,但是因为一些标准函数实际上应该返回那个值,我觉得必须是一个更好的
方式。例如,这是谷歌搜索返回的内容:
浮动PI = std :: atan(1.0f)* 4.0f;
更准确吗?
谢谢
Hi,
I''m doing some maths and I''ve just found that the standard library
does not provide a standard PI value. In older post I see everyone says
you must define it by yourself, but as some of the standard functions
are in fact supposed to return that value, I feel there must be a better
way. For example, here''s what a google search returned:
float PI = std::atan(1.0f) * 4.0f;
Anything more accurate?
Thanks
推荐答案
这应该足够准确。
你可以自己定义一个(3.1415926f浮动就足够了)
然后将其与您使用atan的结果进行比较。
V
-
请在通过电子邮件回复时删除资本''A'
我没有回复最热门的回复,请不要问
This should be accurate enough.
You can define one yourself (3.1415926f for float should be enough)
and then compare this to the result you get using atan.
V
--
Please remove capital ''A''s when replying by e-mail
I do not respond to top-posted replies, please don''t ask
std :: atan(1.0f)应该将pi / 4返回到0.5 ulp以内(尽管我不认为
标准保证这个)。如果浮点基数为2(或4),则乘以4.0仍将给出答案
精确到0.5 ulp。所以我认为
更准确无法实现。也许pi = std :: atan2(0.0f,-1.0f)将会更安全,因为它不依赖于基础。
- Ben
std::atan(1.0f) should return pi/4 to within 0.5 ulp (though I don''t think
the standard guarantees this). Multiplying by 4.0 will still give an answer
accurate to 0.5 ulp if the floating-point base is 2 (or 4). So I would think
that more accuracy is impossible. Perhaps pi = std::atan2(0.0f,-1.0f) would
be slightly safer since it doesn''t depend on the base.
-- Ben
double pi = 4 * std :: atan(1);
这里的任何不准确都可能是由于受限制精度浮动或双倍
而不是这种计算方法。我通过获取22位数字来检查
来自当分配给结果加倍时
与上面计算的pi完全匹配。 (gcc 4.2.1,glibc 2.6.1)
克莱门斯
double pi = 4 * std::atan(1);
Any inaccuracy here is likely due to the limited precision of float or double
rather than this method of computation. I checked by getting 22 digits or so
from http://www.piday.org/million.php and when assigned to double the result
matches exactly to pi as computed above. (gcc 4.2.1, glibc 2.6.1)
Clemens
这篇关于从cmath中提取PI值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!