forked from wedusk101/NumericalAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDerivative.java
62 lines (52 loc) · 2.02 KB
/
Derivative.java
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
/*The following code calculates the derivative of a function
at a point froms ab initio or first principle*/
import java.util.Scanner;
class Derivative
{
static final double EPSILON = 0.000006;
public static double calcDerivative(String func, double val)
{
double ddx = 0.0;
if(func.equalsIgnoreCase("sin x") || func.equalsIgnoreCase("sinx")) // basic trigonometric functions
{
ddx = (Math.sin(val + EPSILON) - Math.sin(val)) / EPSILON;
}
else if(func.equalsIgnoreCase("cos x") || func.equalsIgnoreCase("cosx"))
{
ddx = (Math.cos(val + EPSILON) - Math.cos(val)) / EPSILON;
}
else if(func.equalsIgnoreCase("tan x") || func.equalsIgnoreCase("tanx"))
{
ddx = (Math.tan(val + EPSILON) - Math.tan(val)) / EPSILON;
}
else if(func.equalsIgnoreCase("atan x") || func.equalsIgnoreCase("atanx") || func.equalsIgnoreCase("arctan x") || func.equalsIgnoreCase("arctanx"))
{
ddx = (Math.atan(val + EPSILON) - Math.atan(val)) / EPSILON;
}
else if(func.equalsIgnoreCase("asin x") || func.equalsIgnoreCase("asinx") || func.equalsIgnoreCase("arcsin x") || func.equalsIgnoreCase("arcsinx"))
{
ddx = (Math.asin(val + EPSILON) - Math.asin(val)) / EPSILON;
}
else if(func.equalsIgnoreCase("acos x") || func.equalsIgnoreCase("acosx") || func.equalsIgnoreCase("arccos x") || func.equalsIgnoreCase("arccosx"))
{
ddx = (Math.acos(val + EPSILON) - Math.acos(val)) / EPSILON;
} // end of basic trigonometric functions
return ddx;
}
}
class DriveDerivative
{
public static void main(String args[])
{
String function;
double value = 0.0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter the function which you want to differentiate.");
function = in.nextLine();
System.out.println("Please enter the point where you want to calculate the derivative.");
value = in.nextDouble();
Derivative dr = new Derivative();
System.out.println("The value of the derivative of the function at the given point is " + dr.calcDerivative(function, value) + ".");
in.close();
}
}