Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package NumericalComputing.SecantMethod;
- import java.util.Scanner;
- @interface DaudKakumirizi
- {
- String name() default " ";
- String ID() default " ";
- }
- @DaudKakumirizi(name = "Kakumirizi Daud", ID = "17/BSS/BU/R/0010")
- @SuppressWarnings("ALL")
- public class Secant {
- /**
- *
- * @param function takes value of x and returns f(x)
- * @return
- */
- static float f(float x) {
- /**
- * we are taking equation
- * as x^3+x-1
- */
- float f = (float)Math.pow(x, 3)
- + x - 1;
- return f;
- }
- static void secant(float x1, float x2,
- float E) {
- float n = 0, xm, x0, c;
- if (f(x1) * f(x2) < 0)
- {
- do {
- /**
- * calculate the intermediate
- * value
- */
- x0 = (x1 * f(x2) - x2 * f(x1))
- / (f(x2) - f(x1));
- /**
- * check if x0 is root of equation or not
- */
- c = f(x1) * f(x0);
- /** update the value of interval */
- x1 = x2;
- x2 = x0;
- /** update number of iteration */
- n++;
- /** if x0 is the root of equation then break the loop */
- if (c == 0)
- break;
- xm = (x1 * f(x2) - x2 * f(x1))
- / (f(x2) - f(x1));
- /** repeat the loop until the convergence*/
- } while (Math.abs(xm - x0) >= E);
- System.out.println("Therefore the Root is ---> " + x0);
- System.out.println();
- System.out.println("No. of "
- + "iterations = " + n);
- }
- else
- System.out.print("Can not find a"+ " root in the given inteval");
- }
- /** Driver code */
- public static void main(String[] args) {
- System.out.println("Implementation of Secant Method in Java");
- System.out.println();
- Scanner sc = new Scanner(System.in);
- int highest_degree;
- System.out.println("What is the highest degree of your polynomial? ");
- Scanner input = new Scanner(System.in);
- highest_degree = input.nextInt();
- for (int x = highest_degree; x >= 0; x--) {
- int coeff_deg_x;
- coeff_deg_x = poly_input(x);
- /**System.out.println(coeff_deg_i); */
- }
- Scanner scs = new Scanner(System.in);
- System.out.println("Enter the lower limit of the Interval");
- float x1 = scs.nextFloat();
- System.out.println("Enter the upper limit of the Interval");
- float x2 = sc.nextInt(),
- E = 0.0001f;
- secant(x1, x2, E);
- }
- public static int poly_input(int degree) {
- System.out.println("Please enter coefficient for degree " + degree);
- Scanner input = new Scanner(System.in);
- int coefficient;
- coefficient = input.nextInt();
- return coefficient;
- }
- }
- /**This code is contributed by Kakumirizi Daud */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement