python牛顿法算立方根_牛顿迭代法求a的立方根的C语言程序?

2011-09-21 回答

/* header files */

#include

#include

#include

/* functions */

double cbrt_simple(double x);

double cbrt_newton(double a, double x);

/* main */

int main(void) {

double x2 = 2.0 * 2.0 * 2.0;

double x3 = 3.0 * 3.0 * 3.0;

double x4 = 4.0 * 4.0 * 4.0;

double x5 = 5.0 * 5.0 * 5.0;

printf("%.1fの立方根 (真値 = 2.0)\n", x2);

printf("cbrt: %.16f\n", cbrt(x2));

printf("1/3: %.16f\n", cbrt_simple(x2));

printf("Newton: %.16f\n", cbrt_newton(x2, 10.0));

printf("\n%.1fの立方根 (真値 = 3.0)\n", x3);

printf("cbrt: %.16f\n", cbrt(x3));

printf("1/3: %.16f\n", cbrt_simple(x3));

printf("Newton: %.16f\n", cbrt_newton(x3, 10.0));

printf("\n%.1fの立方根 (真値 = 4.0)\n", x4);

printf("cbrt: %.16f\n", cbrt(x4));

printf("1/3: %.16f\n", cbrt_simple(x4));

printf("Newton: %.16f\n", cbrt_newton(x4, 10.0));

printf("\n%.1fの立方根 (真値 = 5.0)\n", x5);

printf("cbrt: %.16f\n", cbrt(x5));

printf("1/3: %.16f\n", cbrt_simple(x5));

printf("Newton: %.16f\n", cbrt_newton(x5, 10.0));

return EXIT_SUCCESS;

}

/**

* 1/3乗をして立方根を求める

* @param[in] x 実数

* @return x の立方根

*/

double cbrt_simple(double x) {

return pow(x, 1.0 / 3.0);

}

/**

* ニュートン法で立方根を近似する

* @param[in] a 実数

* @param[in] x 解に近そうな値

* @return a の立方根

*/

double cbrt_newton(double a, double x) {

double e;

do {

e = (x * x * x - a) / (3.0 * x * x);

x = x - e;

} while ( fabs(e) > 1.0e-16 );

return x;

}

--------

実行結果:

----------------------------------------------------------------------------------

[wtopia]$ gcc -Wall -O2 -o cbrt cbrt.c [~/src_c]

[wtopia]$ ./cbrt [~/src_c]

8.0の立方根 (真値 = 2.0)

cbrt: 2.0000000000000000

1/3: 2.0000000000000000

Newton: 2.0000000000000000

27.0の立方根 (真値 = 3.0)

cbrt: 3.0000000000000000

1/3: 3.0000000000000000

Newton: 3.0000000000000000

64.0の立方根 (真値 = 4.0)

cbrt: 4.0000000000000000

1/3: 3.9999999999999996

Newton: 4.0000000000000000

125.0の立方根 (真値 = 5.0)

cbrt: 5.0000000000000000

1/3: 4.9999999999999991

Newton: 5.0000000000000000

补充:

没有想到从 Terminal 下面复制到这里面效果这么差劲, 国内的系统果然够烂.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值