-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuad.java
More file actions
64 lines (55 loc) · 2.03 KB
/
Quad.java
File metadata and controls
64 lines (55 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* Dr. Becnel
This program implements a gradient descent like algorithm
using iterative improvement to find the vertex of a
parabola.
The coefficients of the parabola are read from the console
and an approximation to the vertex is displayed to the console.
*/
import java.util.Scanner;
public class Quad {
//===================MAIN===================
// Here we read in the coefficients for the quadratic function.
// We then find an approximation to the vertex and display the result
// to the console.
public static void main(String[] args) {
// read in the coefficients for the quadratic function
System.out.println("Enter the coefficients for the quadratic function y = ax^2+bx+c: ");
Scanner console = new Scanner(System.in);
float a = console.nextFloat();
float b = console.nextFloat();
float c = console.nextFloat();
console.close();
// find the x coordinate of the vertex of the parabola
float x = findVertex(a,b);
// display the vertex approximation
System.out.println("The vertex of hte parabola is approximately:");
System.out.println("(" + x +", " + a*x*x+b*x+c + ")");
}
//------------------findVertex--------------------
//
public static float findVertex(float a, float b) {
double x = Math.random()*20+-10;
double stepSize = 1;
while (stepSize > 0.1) {
double der = fprime(a,b,x);
double newX = x;
if (der == 0) {
stepSize = 0;
} else if (der > 0) {
newX = x - stepSize;
}
else
newX = x + stepSize;
if (der * fprime(a,b,newX) < 0)
stepSize = stepSize / 2.0;
x= newX;
}
return (float) x;
}
//---------------fprime----------------------
// This function returns the derivative of the quadratic
// function at x.
public static double fprime(float a, float b, double x) {
return 2*a*x+b;
}
}