我正在嘗試使用Newton Tangent Method來求解給定方程。切線方法的工作原理是假設解決方案處於a-b區間的某處,其中給出a和b並且該函數在[a,b]區間內是連續的。 我已經寫了程序,它的工作正常,但現在我必須爲它做一個GUI,並且必須從文本文件中讀取公式。 我的問題是,我不知道如何從.txt文件獲取公式,並將其設置爲函數方法的返回值。這應該適用於任何給定的等式。 下面是我的公式代碼:x^3 -4 * x^2 + 5 * x^1 -12
從.txt文件讀取ecuation並將其設置爲方法返回
下面是代碼:
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);
}
解決它。謝謝大家的幫助:)
可能重複[有沒有在Java中的eval()函數?(http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – alfasin
了現在的一個問題,當我從按鈕內部調用方法時,我得到一個java.lang.NullPointerException,我不知道如何解決它。我不認爲我發送任何空值。 – user3197521