Skip to content

Instantly share code, notes, and snippets.

@akirad
Last active August 29, 2015 13:55
Show Gist options
  • Save akirad/8703916 to your computer and use it in GitHub Desktop.
Save akirad/8703916 to your computer and use it in GitHub Desktop.
// [課題]
// 5 = -0.00003*X^4 + 0.0034*X^3 - 0.1257*X^2 + 1.6351*X + 0.000000000003 のXを求める。
// いろいろ方法はありそうだが、メジャーな数値計算法である、ニュートン法で試してみた。
// 具体的には、f(X) = -0.00003*X^4 + 0.0034*X^3 - 0.1257*X^2 + 1.6351*X + 0.000000000003 - 5 として、
// f(X) = 0 となる解Xを、ニュートン法、つまり、X[n+1] = X[n] - f(X)/f'(X) をもとに、繰り返し計算を行った。
public class Newton {
public static void main(String[] args) {
double x = 1; // 出発値
double new_x;
double EPS = 1.0e-5; // 許容誤差
int counter = 0;
int MAX = 100000; // 許容誤差内に収まるまで、10万回繰り返し計算を行う。このMAX回数を超えたら諦める。
while(true){
counter++;
new_x = x - f(x)/df(x);
if(Math.abs(new_x - x) < EPS) break;
if(counter == MAX) {
System.out.println("Can't get the answer...");
return;
}
x = new_x;
}
System.out.println("Result: " + new_x);
// xが1の時、解は、4.3455191757503275 になった。
// xが20の時、解は、19.35631524863516 になった。
// この二つが、求めたい解である。
}
static double f(double x){
return -0.00003*Math.pow(x,4) + 0.0034*Math.pow(x,3) - 0.1257*Math.pow(x,2) + 1.6351*x + 0.000000000003 - 5.0;
}
static double df(double x){
// f'(x) = -0.00012*x^3 + 0.0102*x^2 - 0.2514*x + 1.6351
return -0.00012*Math.pow(x,3) + 0.0102*Math.pow(x,2) - 0.2514*x + 1.6351;
}
}
public class Newton1 {
public static void main(String[] args) {
double TOLERANCE = 1.0e-5;
int MAX = 100000;
for(int start = 0; start <= 50; start++){
double x = start;
double new_x;
int counter = 0;
while(true){
counter++;
new_x = x - f(x)/df(x);
if(Math.abs(new_x - x) < TOLERANCE) break;
if(counter == MAX) {
System.out.println("Can't get the answer...");
return;
}
x = new_x;
}
System.out.println("Result: " + new_x + " When start with x= " + start);
}
}
static double f(double x){
return -0.00003*Math.pow(x,4) + 0.0034*Math.pow(x,3) - 0.1257*Math.pow(x,2) + 1.6351*x + 0.000000000003 - 5.0;
}
static double df(double x){
return -0.00003*4*Math.pow(x,3) + 0.0034*3*Math.pow(x,2) - 0.1257*2*x + 1.6351;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment