📄 solver.java
字号:
package edu.nyu.cims.hw4;
import edu.nyu.cims.hw4.IFunction;
public class Solver {
/**
* This method can be used to solve the equation f(x) = 0. We use the
* divide and concur approach. The solver takes a range where to look for solution.
* the function at the ends of the range should take opposite signs. We stop
* refining the solution once we found a point such that |f(x)| is smaller
* than some tolerance.
* @param f The function we need to solve.
* @param x0 The left boundary in the range where we will look for the solution.
* @param x1 The right boundary in the range where we will look for the solution.
* @param tolerance The tolerance for the stopping condition.
* @return The value x that solves the equation.
* @throws Exception If an error occured in the process.
*/
public static double findZero(IFunction f, double x0, double x1, double tolerance ) throws Exception{
// if the function value at x0 or x1 is zero we will return that value.
if ( f.value(x0) == 0 ){ return x0; }
if ( f.value(x1) == 0 ){ return x1; }
// checking that the function takes opposite signs at x0 and x1
if ( Math.signum( f.value( x0 ) ) == Math.signum( f.value( x1 ) ) ){
throw new Exception("The function must take opposite signs at x0 and x1." );
}
// Setting some variables.
double left = x0;
double right = x1;
double fright = f.value( right );
double middle = 0.5 * (left + right);
double fmiddle = f.value( middle );
while ( Math.abs( fmiddle ) > tolerance ){
// cutting the range by half.
if ( Math.signum( fmiddle ) == Math.signum( fright) ){
right = middle;
fright = fmiddle;
} else {
left = middle;
}
// calculating the new middle and f middle.
middle = 0.5 * (left + right );
fmiddle = f.value( middle );
}
return middle;
}
/*public static void main(String[] args) throws Exception{
// Suppose we want to solve the equation x^2 = 36 (solution 6).
IFunction f = new IFunction(){
public double value(double x) throws Exception {
return x * x - 36;
}
};
System.out.println("Solution: " + findZero(f, 0, 11.56, 1e-6) );
System.out.println("Solution: " + findZero(f, -100, 0, 1e-6) );
}*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -