\(\displaystyle{ 2+\cos(\frac{\pi}{2}\cdot x)-2x=0}\)
Problem mam taki, że nie wiem czy algorytm jest dobry, ponieważ dla \(\displaystyle{ \epsilon=const}\) i \(\displaystyle{ x_0 = 1}\) lub innego \(\displaystyle{ x_0}\) nieparzystego błąd względny ciągle wynosi 0. Nie wiem czy to tak ma być, czy mam błąd w obliczaniu...
Oto kod:
Kod: Zaznacz cały
package newton;
/**
* Netwon's method implementation
*/
public class Newton {
private static final double realRoot = 1.0;
public static double f(double x) {
return 2.0 + Math.cos(Math.PI / 2.0 * x) - 2.0 * x; // funkcja f
}
public static double fp(double x) {
return -1 / 2 * Math.PI * Math.sin((Math.PI * x) / 2) - 2; // pochodna f
}
public static double round(double value, int places) {
if (places < 0) {
throw new IllegalArgumentException();
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
public static double getRelativeError(double x) {
return Math.abs((x - realRoot) / realRoot);
}
public static void main(String[] args) {
double x, x0, e, h;
x0 = 5;
e = 0.001;
int n = 0;
do {
x = x0 - f(x0) / fp(x0);
h = Math.abs(x - x0);
x0 = x;
n++;
} while (h > e);
System.out.println("Newton");
System.out.println("x=" + x);
System.out.println("n=" + n);
double relativeError = getRelativeError(x);
System.out.println("Blad wzgledny: " + relativeError);
System.out.println("Blad wzgledny: " + round(relativeError * 100, 35) + "%");
}
}