Newton's Method
Page 1 of 1
Newton's Method
This program I wrote to do the table calculating Newton's Method.
You can edit the equation and variables to do the work.
Output:
You can edit the equation and variables to do the work.
- Code:
import java.util.Scanner;
/**
*
* @author ThienDinh
*/
public class Homework {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner in = new Scanner(System.in);
/*
* Newton's Method
* Round off to 8th decimal, each calculation
* Function using is f(x) = 3x^3 - 9x + 2 and its derivative f'(x) = 9x^2 - 9
* First picked x = 0 -> fx = 2 -> dfx = -9 (Calculated by hand)
*/
double x = 0;
double fx = 2;
double dfx = -9; // dfx : f'
System.out.print("n = ");
int n = in.nextInt();
System.out.println("--------------------------------------------------------------------");
System.out.printf("n = 1\t");
System.out.printf("x: %.8f\t", x);
System.out.printf("f(x): %.8f\t", fx);
System.out.printf("f'(x): %.8f\n", dfx);
for (int i = 2; i <= n; i++)
{
String temp = "";
System.out.println("--------------------------------------------------------------------");
System.out.printf("n = %d\t", i);
temp = "" + String.format("%.8f", x - (fx / dfx)); // Xn = X - (Fx / F'x)
x = Double.parseDouble(temp);
System.out.printf("x: %.8f\t", x);
temp = "" + String.format("%.8f", 3 * Math.pow(x, 3) - 9 * x + 2); // Function
fx = Double.parseDouble(temp);
System.out.printf("f(x): %.8f\t", fx);
temp = "" + String.format("%.8f", 9 * Math.pow(x, 2) - 9); // Derivative funtion
dfx = Double.parseDouble(temp);
System.out.printf("f'(x): %.8f\n", dfx);
}
}
}
Output:
n = 5
--------------------------------------------------------------------
n = 1 x: 0.00000000 f(x): 2.00000000 f'(x): -9.00000000
--------------------------------------------------------------------
n = 2 x: 0.22222222 f(x): 0.03292183 f'(x): -8.55555556
--------------------------------------------------------------------
n = 3 x: 0.22607023 f(x): 0.00002975 f'(x): -8.54003026
--------------------------------------------------------------------
n = 4 x: 0.22607371 f(x): 0.00000003 f'(x): -8.54001610
--------------------------------------------------------------------
n = 5 x: 0.22607371 f(x): 0.00000003 f'(x): -8.54001610
BUILD SUCCESSFUL (total time: 6 seconds)
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
Sat Feb 15, 2014 10:12 am by doriperni
» Sync2 V2.20.1312 X86x64.rar.rar
Fri Feb 14, 2014 7:37 pm by carmibire
» 9.1 Inheritance Hierarchies
Tue Feb 26, 2013 12:50 pm by ThienDinh
» Useful website
Sat Dec 08, 2012 6:52 pm by tpham1991
» The Machine that Changed the World: Giant Brains. 1992 Documentary
Sat Dec 08, 2012 2:16 am by ThienDinh
» Problems in practice test.
Thu Dec 06, 2012 2:32 pm by ThienDinh
» Newton's Method
Mon Dec 03, 2012 8:32 pm by ThienDinh
» Console Calc
Sun Dec 02, 2012 5:57 pm by Petahwil
» Law Of Cosines
Sat Dec 01, 2012 4:54 pm by Petahwil