错误答案在计算数字的CPP的n次方根 [英] Wrong answer while calculating the nth root of number in cpp

查看:186
本文介绍了错误答案在计算数字的CPP的n次方根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计算使用标准库法战俘正整数的第n根()。这里是我的程序代码段:

I am calculating the n'th root of a positive integer using standard library method pow() .Here is the snippet from my program :

double x,y;
x=pow(64,(1.0/3));
int z;
printf("x=%lf\n",x);
z=(int)x;
printf("%d\n",z);

不过,虽然发现64的X立方根打印为4.000000,而ž为3。为什么会这样?

But while finding cube root of 64. X is printed as 4.000000 while z as 3. Why so ?

有人可以提供一个更好的算法,对于相同的?

Can someone suggest a better algorithm , for the same ?

推荐答案

INT 覆盖几轮下来。由于浮点运算是不准确的,计算可能是3.999999 ......

The int override rounds down. Since floating point operations are inaccurate, the calculation may be 3.999999...

<打击>使用圆(X)来得到正确的结果。

Use round(x) to get the correct result.

由于你总是想圆的的,你可以同时使用地板(INT) - 但你一旦碰到观测误差的浮点计算导致不稳定的的价值不大 - 这是在10 -15 为尺寸的计算。使用一个微小的小量的价值以抵消。

Since you always want to round down, you can use both floor and (int) -- but you run into the observed error as soon as the instability of floating point calculations results in a slightly less value -- something in the order of 10-15, for double sized calculations. Use a tiny epsilon value to counteract that.

请注意,小量忽悠值低于涉及到显著数字在你原来的号码的数量。对于较大的数字,你需要一个更小的小量。

Note that the epsilon "fudge" value below will relate to the number of significant digits in your original number. For larger numbers, you need a smaller epsilon.

#include <stdio.h>
#include <string.h>
#include <math.h>

int main (void)
{
    double x;
    int z;

    x=pow(64,(1.0/3));
    printf("x=%lf\n",x);
    printf("x=%.30lf\n",x);

    z=(int)x;
    printf("%d\n",z);

    z=(int)(x+0.000000000000005);
    printf("%d\n",z);

    x=pow(64,(1.0/4));
    printf("x=%lf\n",x);
    printf("x=%.30lf\n",x);

    z=(int)x;
    printf("%d\n",z);

    z=(int)(x+0.0000000000000005);
    printf("%d\n",z);

    return 1;
}

结果,为的1/3和1/4,在权力

results, for powers of 1/3 and 1/4, in

x=4.000000
x=3.999999999999999555910790149937
3
4
x=2.828427
x=2.828427124746190290949243717478
2
2

这篇关于错误答案在计算数字的CPP的n次方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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