[英]Trying to approximate the value of natural log e and the number of term use to calculate e
package homework1C;
public class Homework1C {
public static void main(String[] args){
double term =2,sum;
int n;
final double difference = 0.0000000001;
double x;
for(sum=0.0,n=0;term > difference;n++){
x = find_n_fact(n);
term=1.0/x;
sum+=term;
n++;
}
System.out.printf("e : %f\n", sum);
System.out.printf("term : %d\n", n);
}
public static int find_n_fact(int n){
int i;
int fact = 2;
for(i = n; i>2;i--){
fact *= i;
}
return fact;
}
}
這就是我被要求做的事情:寫另一個Java應用程序來查找並顯示e的近似值(自然對數)。 使用以n為2的以下近似公式,將n遞增1,直到e的兩個連續值之差小於0.0000000001,不僅顯示近似值,還顯示最后近似值中使用了n個項。 計算公式為:e = 1/0的近似值! + 1/1! + 1/2! + 1/3! + ...,其中n! 是階乘
這是我目前對該程序的輸出
e : 1.043081
term : 20
我究竟做錯了什么 ? 答案應該是
e: 2.71828
term: 15
如何解決呢?
當n為0或1時,您的階乘函數find_n_fact
不正確。
您犯了幾個錯誤:
main()
的for循環中將n遞增兩次,這是無稽之談。 這是適合您的完整代碼:
public class Homework1C {
public static void main(String[] args) {
double term = 2, sum = 0;
final double difference = 0.0000000001;
int n;
for (n = 0; term > difference; n++) {
term = 1.0 / find_n_fact(n);
sum += term;
}
System.out.printf("e : %f\n", sum);
System.out.printf("term : %d\n", n);
}
public static double find_n_fact(int n) {
if (n == 0 || n == 1)
return 1.0;
return n * find_n_fact(n - 1);
}
}
階乘方法的迭代版本在這里:
public static double find_n_fact(int n) {
double i, fact = 1;
if(n < 0) // for negative numbers, factorial is nonsense.
return -1;
for (i = n; i > 1; i--)
fact *= i;
return fact;
}
總而言之,以下項是1/n!
是1/(n+1)!
。 這意味着沒有理由從頭開始重新計算(n+1)!
從頭計算(n+1)!
),而只需將當前項值除以下一個n
值即可; 即循環內容只需要
term /= n;
sum += term;
在循環開始之前,您將n,term和之和初始化為1(因為1/0!為1)。 當然,將n++
排除在循環之外,因為for
語句本身包含n++
。 這種方法擺脫了您的find_n_fact()
函數及其中的錯誤。 (次要說明: 1e-10
比0.0000000001
編寫更方便,並且具有相同的值。)還有一個建議:添加如下語句
System.out.printf("sum : %12.10f term: %12.10f 1/t: %12.10f, n: %d\n", sum, term, 1/term, n);
在調試時進入循環 這將使諸如多余的n++
之類的錯誤和階乘函數中的錯誤變得顯而易見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.