Skip to content

Instantly share code, notes, and snippets.

@pif
Created September 29, 2010 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pif/602354 to your computer and use it in GitHub Desktop.
Save pif/602354 to your computer and use it in GitHub Desktop.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ostap.chyselni;
/**
*
* @author Ostap.Andrusiv
*/
public class Iterations {
/**
* @param args
*/
private static double epsilon;
public static String output;
public static int n;
public Iterations() {
prepare();
}
/**
* Function who's 0 we are to find
*
* @param x
* @return result of f(x)
*/
private static double f(double x) {
// f(x) = x-sin(x)-0.25;
return x - Math.sin(x) - 0.25d;
}
/**
* derivative of f(x)
*
* @param x
* @return calculates derivative of f() in x
*/
private static double fD(double x) {
// f(x) = x-sin(x)-0.25;
// f'(x) = 1-cos(x);
return 1 - Math.cos(x);
}
private static void prepare() {
epsilon = 0.00001d;
output = "";
n=0;
}
/**
* Secant Method implementation
*
* @param x
* , x1 are boundaries of the secant
* @param epsilon
* approximation
* @return root of equation f(x)=0;
*/
public static double secantMethod(double x, double x1) {
prepare();
while (Math.abs(x1 - x) > epsilon) {
x = x1 - (x1 - x) * f(x1) / (f(x1) - f(x));
x1 = x - (x - x1) * f(x) / (f(x) - f(x1));
output += x1 + "\n";
++n;
}
return x1;
}
/**
* finds root by Newton's Method
*
* @param x
* starting argument
* @param epsilon
* approximation
* @return root
*/
public static double NewtonsMethod(double x) {
prepare();
double x1 = x - f(x) / fD(x);
while (Math.abs(x - x1) > epsilon) {
x = x1;
x1 = x - f(x) / fD(x);
output += x1 + "\n";
++n;
}
return x1;
}
/**
* equivalent f(x)=0 : x=psi(x);
*
* @param x
* argument
* @return x for next iteration;
*/
private static double phi(double x) {
// that's because we have f(x)=x-sin(x)-0.25;
return Math.sin(x) + 0.25;
}
/**
* finds root by Simple Iteration Method
*
* @param x
* starting argument
* @param epsilon
* approximation
* @return root
*/
public static double SimpleIterationMethod(double x) {
// f(x) = x-sin(x)-0.25
// f(x) == 0
// f(x) + x == x
// phi(x) == x=-sin(x)-0.25
//phi' = |-cos(x)|<1
prepare();
double x1 = phi(x);
while (Math.abs(x1 - x) > epsilon) {
x = x1;
x1 = phi(x);
output += x1 + "\n";
++n;
}
return x1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment