用巴比伦法计算 $\sqrt[3]{x}$
Calculating $\sqrt[3]{x}$ with Babylonian method
考虑一下我在 C:
中实现巴比伦方法的尝试
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
x=27 的结果是:0.0000?
我的错误在哪里?
虽然函数 returns 是 int
,但该值是使用 wrong format specifier、%f
而不是 %d
.
打印的
将签名(和姓名,如果可以的话)更改为类似 this
的内容
double cube_root(double x) { ... }
或者更改格式说明符,如果您真的想要 int
。
根据 tutorialspoint 的解释,其基本思想是实施牛顿拉夫森法来求解非线性方程,恕我直言,下面的代码更清楚地显示了这一事实。由于已经有一个被接受的答案,我添加这个答案只是为了将来参考。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
这里对比题目原代码更明显的是,x
和y
是bounds,正在完善中,直到找到足够准确的解。
通过修改 while 块中更新 y 的行,此代码也可用于求解类似的方程式。例如,要求平方根,此行应如下所示:y = a / x
.
考虑一下我在 C:
中实现巴比伦方法的尝试int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
x=27 的结果是:0.0000? 我的错误在哪里?
虽然函数 returns 是 int
,但该值是使用 wrong format specifier、%f
而不是 %d
.
将签名(和姓名,如果可以的话)更改为类似 this
的内容double cube_root(double x) { ... }
或者更改格式说明符,如果您真的想要 int
。
根据 tutorialspoint 的解释,其基本思想是实施牛顿拉夫森法来求解非线性方程,恕我直言,下面的代码更清楚地显示了这一事实。由于已经有一个被接受的答案,我添加这个答案只是为了将来参考。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
这里对比题目原代码更明显的是,x
和y
是bounds,正在完善中,直到找到足够准确的解。
通过修改 while 块中更新 y 的行,此代码也可用于求解类似的方程式。例如,要求平方根,此行应如下所示:y = a / x
.