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 下面复制到这里面效果这么差劲, 国内的系统果然够烂.