Reputation: 1
I am trying to solve an given equation using Newton Tangent Method. The Tangent Method works by assuming the solution is somewhere in the a-b interval where a and b are given and that the function is continuous on the [a,b] interval.
I already wrote the program and it's working fine but now I have to make a GUI for it and the equation must be read from a text file.
My issues is that I do not know how to get the equation from the .txt file and set it as return for my function method. This should work for any given equation.
Below is my code for the equation: x^3 -4 * x^2 + 5 * x^1 -12
Here is the code:
static double f(double x) { // the function from the .txt file
//return Math.pow(x, 3) - 4* Math.pow(x,2) + 5 * Math.pow(x, 1) - 12;
return x * x * x - 4 * x * x + 5 * x - 12;
}
static double df(double x) { // the function derivative
return 3 * x * x - 8 * x + 5;
}
static String metTangent() {
double b = 4, c, reduceIntervalBy, precision = 0.00000000001;
// reduceIntervalBy holds the value of how much should the interval be reduced by, starting from b to a, so from right to left
DecimalFormat decimalformat = new DecimalFormat("#.00000000000000");
do {
c = b - f(b) / df(b);
//System.out.println(c);
reduceIntervalBy = b - c;
b = c;
} while (reduceIntervalBy > precision );
return "The solution is: " + decimalformat .format(c);
}
Solved it. Thanks everyone for help :)
Upvotes: 0
Views: 187
Reputation: 12610
To avoid having to write a parser, one can leverage an implementation of the Java Expression Language, e.g. https://uel.java.net/get-started.html. Alternatively, the Java Scripting API can do the same thing. Both is a little overkill for the small task but should quickly get you started.
Edit: See @robin's answer for an example using the scripting API.
Upvotes: 2
Reputation: 1925
you can use the below method to read the equation from a text file.
static String getEquation () throws Exception
{
Scanner in = new Scanner(new FileReader("C:\\test1.txt"));
StringBuffer br = new StringBuffer();
while(in.hasNext())
{
br.append(in.next());
}
return br.toString();
}
Then to parse the equation and value to be evaluated to the below function.
static Object f(double x,String eq) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.put("x",x);
return engine.eval(eq);
}
Upvotes: 3
Reputation: 7521
I suspect this task is MUCH harder than you imagine, these are the basic steps you need to look at implementing:
Good Luck
Upvotes: 1