Implementation of Chord Method written in Java.
IN -3 0 0.00001 OUT : -1.0 f(x): -2.0 X: -2.0 f(x): -1.0 X: -2.3333333333333335 f(x): -0.22222222222222188 X: -2.4 f(x): -0.04000000000000026 X: -2.4117647058823533 f(x): -0.006920415224912602 X: -2.413793103448276 f(x): -0.0011890606420928984 X: -2.4141414141414144 f(x): -2.0406081012080968E-4 X: -2.414201183431953 f(x): -3.501277966366789E-5
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 intervalBegin; double intervalEnd; double x; double precision; System.out.print("Enter begining of interval: "); intervalBegin = reader.nextDouble(); System.out.print("Enter end of interval: "); intervalEnd = reader.nextDouble(); System.out.print("Enter precision of method: "); precision = reader.nextDouble(); if(function(intervalBegin) * function(intervalEnd) > 0.0d){ System.out.println("Function has same signs at ends of interval"); return; } x = (intervalBegin * function(intervalEnd) - intervalEnd * function(intervalBegin)) / (function(intervalEnd) - function(intervalBegin)); while(Math.abs(function(x)) > precision){ System.out.println("X: " + x + " f(x): " + function(x)); if(function(intervalBegin) * function(x) < 0){ x = (x * function(intervalBegin) - intervalBegin * function(x)) / (function(intervalBegin) - function(x)); }else{ x = (x * function(intervalEnd) - intervalEnd * function(x)) / (function(intervalEnd) - function(x)); } } } static double function(double x) { //x^2 + 2x -1 return x * (x + 2) - 1; } }
Java Chord Method