我試圖計算辛普森的規則來得到準確性爲< 10^-6。但是每當函數運行時,由於0/sin(0),我得到一個NaN或DNE錯誤。當I = 1時,如何解決這個錯誤? **我的編輯功能,包括當我== 1計算辛普森規則錯誤<10^-6
public static double simpsonsRuleFunction1(double valueN, double valueA, double valueB, double valueDx) {
double e = 0.0;
double simpsonsRule = 0.0;
double valueHolder = 0.0;
valueN = 2;
valueA = 0;
valueB = (Math.PI)/2;
for(int i = 1; i<=valueN+1 ; i++){
valueDx = (valueB-valueA)/valueN;
e = valueA + ((i-1)*valueDx);
if (i==1) {
// Limit as x -> 0
simpsonsRule += Math.pow(10,-10);
}
else if ((i % 2 == 0) && (i > 1) && (i < valueN+1)) {
simpsonsRule += 4*(e/((Math.sin(e))));
}
else if ((i % 2 != 0) && (i > 1) && (i < valueN+1)) {
simpsonsRule += 2*(e/((Math.sin(e))));
}
else if (i == valueN+1) {
simpsonsRule += (e/((Math.sin(e))));
}
}
simpsonsRule = simpsonsRule *((valueDx)/3);
while(Math.abs(valueHolder - simpsonsRule) > Math.pow(10,-6)) {
System.out.println("\nValueHolder" + valueHolder);
valueHolder = simpsonsRule;
valueN +=2;
valueDx = (valueB-valueA)/valueN;
simpsonsRule = 0;
for(int i = 1; i<=valueN + 1; i++){
e = valueA + ((i-1)*valueDx);
if (i==1) {
// Limit as x -> 0
simpsonsRule += Math.pow(10,-10);
}
else if (i % 2 == 0) {
simpsonsRule += 4*(e/((Math.sin(e))));
}
else if ((i % 2 != 0) && (i > 1) && (i < valueN + 1)) {
simpsonsRule += 2*(e/((Math.sin(e))));
}
else if (i == valueN + 1) {
simpsonsRule += (e/((Math.sin(e))));
}
}
simpsonsRule = simpsonsRule *((valueDx)/3);
}
return valueN;
}
我需要N個錯誤<10^-6的區間。 –
N只是正數,偶數 –