#/*********************************************************** # newt2.rb -- Newton (ニュートン) 法 #***********************************************************/ def f( x ) # $f(x) = 0$ を解く関数 $f(x)$ return Math::atan2(x - 1, 1) end def newton( x ) # 初期値 $x$ から $f(x) = 0$ の解を求める fx = f(x) while (fx != 0) df = f(x + fx) - fx; h = fx * fx / df x_prev = x; fx_prev = fx; i = 0 begin x = x_prev - h; fx = f(x); h /= 2; i += 1 printf("(%d) x = % -24.16g f(x) = % -.2g\n",\ i, x, fx) end while (fx.abs > fx_prev.abs) if (i == 1 && x == x_prev); break; end end return x end printf("atan(x - 1) = 0 を解きます.\n") printf("初期値 = "); x = gets.to_f x = newton(x) printf("解は %g です.\n", x) exit 0