2015-01-16 21 views
0

我正在嘗試使用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);  
} 

解決它。謝謝大家的幫助:)

+1

可能重複[有沒有在Java中的eval()函數?(http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – alfasin

+0

了現在的一個問題,當我從按鈕內部調用方法時,我得到一個java.lang.NullPointerException,我不知道如何解決它。我不認爲我發送任何空值。 – user3197521

回答

1

我懷疑這個任務是比你想象的,這些都是你需要看落實的基本步驟更難:

  1. 閱讀從一個文本文件中的公式作爲一個字符串
  2. 編寫一個解析器,使這個字符串中的某些java對象結構代表一個路徑,以評估給定值的等式。 (這是很難的部分 - 嘗試尋找'下降解析器'和'分流碼算法'的來源
  3. 一旦你有了這個結構可以評估任何x的方程,那麼牛頓的方法就像你一樣容易實現。

好運

3

您可以使用下面的方法從文本文件中讀取公式。

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(); 
} 

然後解析方程和值來評估下面的函數。

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); 
} 
+0

工作,謝謝! – user3197521

+0

有一個問題,當我從按鈕內部調用方法時,我得到一個java.lang.NullPointerException,我不知道如何解決它。我不認爲我發送任何空值。 – user3197521

+0

想通了。 – user3197521

相關問題