[英]How can I increase my code's robustness and efficiency to calculate limit
我編寫了一個代碼來計算以下系列的限制:
Un+1 = Un - MyFunction1(Un)/MyFunction2(Un)
有沒有辦法可以修改我的代碼以提高其穩健性和效率? 我正在考慮添加一個 Try Catch 語句來檢查分母是否為零。 但不確定這是否是正確的做法。 還有其他建議嗎?
給我的條件是:
假定代碼中使用的以下兩個函數來自庫:
extern double MyFunction1(double x, double dConstant);
extern double MyFunction2(double x, double dConstant);
#include <iostream>
#include <math.h>
int main(){
int i=0;
double dU0=10.0;
double dU1=0.0;
for (i=0 ; i<30 ; i++) {
if(MyFunction2 (dU0,5.0) != 0.0) {
dU1 = dU0 - MyFunction1(dU0,5.0)/ MyFunction2(dU0,5.0);
}
if (fabs(dU1 - dU0)<0.1){
break;
}
dU0=dU1;
}
if (i<30){
std::cout<< "The result of the series is: " << dU1 << '\n';
}
else{
std::cout<< "The series does not converge\n";
}
return 0;
}
檢查除數是否為零
從計算上講,由於機器精度的限制,您不應該將浮點值與數字零0
之間的差異進行比較。 總是打賭比較你的結果是在一個非常小的公差范圍內。 喜歡
fabs(dU1 - dU0)<1e-10
這總是讓你更安全,因為這個數字非常接近機器精度1e-308
(取決於你的機器),它仍然不會被表示為適當的零。 此外,除以這個非常小的數字也可能會破壞您的結果。
休息
但是,它不是一個很大的優化,您可以通過在 for 循環本身中檢查for (i=0; i<30 && fabs(dU1 - dU0)<1e-10; i++)
來避免代碼內部的中斷
宏
鑒於您的 function 非常小,例如“x 2 + 5x + 6”,那么您可以為其編寫一個宏,以避免在運行時的每次迭代中調用 function。 宏將通過減少運行時負載來替換編譯時本身的值。
#define MyFunction2(x,y) x*x - 5*x + 6
#define MyFunction1(x,y) 2*x - 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.