Implementation of Secant Method written in Java.
IN -3 -1 0.0000001 OUT X: -3.0 f(x): 2.0 X: -2.0 f(x): -1.0 X: -3.0 f(x): 2.0 X: -2.3333333333333335 f(x): -0.22222222222222188 X: -2.4 f(x): -0.04000000000000026 X: -2.4146341463414633 f(x): 0.0011897679952406204 X: -2.41421143847487 f(x): -6.007286838749515E-6
import java.util.Scanner; // ? 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); double xn1; //x_(n - 1) double xn; //x_n double x; double precision; System.out.print("Enter begining of interval: "); xn1 = reader.nextDouble(); System.out.print("Enter end of interval: "); xn = reader.nextDouble(); System.out.print("Enter precision of method: "); precision = reader.nextDouble(); if (function(xn1) * function(xn) > 0.0d) { System.out.println("Function has same signs at ends of interval"); return; } x = xn1; while(Math.abs(function(x)) > precision){ System.out.println("X: " + x + " f(x): " + function(x)); x = xn - ((function(xn) * (xn - xn1)) / (function(xn) - function(xn1))); xn1 = xn; xn = x; } } private static double function(double x) { //x^2 + 2x -1 return x * (x + 2) - 1; } }