简体   繁体   English

C 的 pow() 中参数的精度

[英]precision of argument in pow() of C

Here's a C code;这是一个C代码;

#include<stdio.h>
#include<math.h>
int main()
{
    double n=10.0;
    double automatic = pow(10.0,log10(n)-log10(5.0));
    printf("%.9lf\n",log10(n)-log10(5.0));
    printf("%.9lf\n",pow(10.0,0.30102996));
    double manual = pow(10.0,0.30102996);
    printf("%.9lf %lf\n",automatic, floor(automatic));
    printf("%.9lf %lf\n",manual,floor(manual));
    return 0;
}

Output is:输出是:

0.301029996
1.999999836
2.000000000 1.000000
1.999999836 1.000000

From output I can infer that in pow(x,y) y is rounded off to 6 digits because it's signature is as pow(double x, double y) so that 0.301029996 becomes 0.301030 and that's why value of automatic is 2.000000000 otherwise it would be same as manual.从输出我可以推断 pow(x,y) y 被四舍五入到 6 位数字,因为它的签名是 pow(double x, double y) 所以 0.301029996 变成 0.301030 这就是为什么 automatic 的值是 2.000000000 否则它会是与手册相同。

My questions:我的问题:

  1. Is my inferation correct?我的推断是否正确?
  2. If answer to first question is true then how can we bypass this rounding-off to achieve more accurate results?如果第一个问题的答案为真,那么我们如何绕过这种舍入以获得更准确的结果?

pow does not round to 6 digits. pow不四舍五入到 6 位数。 It uses double precision, which for an IEEE double is 52 bits of significand (roughly 15 decimal places).它使用双精度,对于 IEEE 双精度是 52 位有效数字(大约 15 位小数)。 It may or may not be accurate to the last digit at that precision, but it's usually close.它可能准确也可能不准确到该精度的最后一位数字,但通常很接近。

The exact value of the base-10 log of 2 is close to 0.301029995663981195213738894724 (source: Wolfram Alpha ).以 10 为底的对数 2 的精确值接近0.301029995663981195213738894724 (来源: Wolfram Alpha )。 It is an irrational number, and so cannot be exactly represented by any digit system (decimal or binary).它是一个无理数,因此不能用任何数字系统(十进制或二进制)精确表示。

Your results show that log10(n)-log10(5.0) has returned a value that's closer to the exact mathematical base-10 log of 2, than 0.30102996 is.您的结果显示log10(n)-log10(5.0)返回的值比0.30102996更接近 2 的精确数学基数 10 对数。 The reason you got 1.999999836 is that you manually made your value less accurate when you replaced it with 0.30102996 .你得到1.999999836的原因是当你用0.30102996替换它时,你手动使你的值不太准确。 Which isn't the rounded value, btw - count the 9s.这不是四舍五入的值,顺便说一下 - 数 9。

Your call pow(10.0,log10(n)-log10(5.0)) has returned a result which is very slightly less than 2 (as show by the floor ), but close enough that it rounds to 2 at 9 places.您的呼叫pow(10.0,log10(n)-log10(5.0))返回的结果略小于2 (如floor所示),但足够接近以在 9 处四舍五入为 2。 You are not going to get better than this using the double type.使用 double 类型你不会比这更好。

So I don't really know what you mean by "avoid the rounding off".所以我真的不知道你所说的“避免四舍五入”是什么意思。 If you don't want to make the value less accurate, don't manually round it to 9 places, and certainly don't miss out any digits when you copy it;-)如果你不想让这个值更不准确,不要手动将它四舍五入到 9 位,并且在复制时当然不要遗漏任何数字;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM