<C++程式語言 >例題4-1 梯行法(Trapezoidal method) 計算 exp(x) 在[0 , 1] 的定積分
// C++ program to implement Trapezoidal rule
#include<stdio.h>
#include<math.h>
// A sample function whose definite integral's
// approximate value is computed using Trapezoidal
// rule
float y(float x)
{
// Declaring the function f(x) = 1/(1+x*x)
return exp(x);
}
// Function to evalute the value of integral
float trapezoidal(float a, float b, float n)
{
// Grid spacing
float h = (b-a)/n;
// Computing sum of first and last terms
// in above formula
float s = y(a)+y(b);
// Adding middle terms in above formula
for (int i = 1; i < n; i++)
s += 2*y(a+i*h);
// h/2 indicates (b-a)/2n. Multiplying h/2
// with s.
return (h/2)*s;
}
// Driver program to test above function
int main()
{
// Range of definite integral
float x0 = 0;
float xn = 1;
// Number of grids. Higher value means
// more accuracy
int n = 10;
float ans1=trapezoidal(x0, xn, n);
float ans2=exp(1)-exp(0);
printf("Value of integral is %6.4f\n",ans1);
printf("Real value of integral is %6.4f\n",ans2);
printf("Error tolerance is %6.6f\n",fabs(ans2-ans1));
return 0;
}
輸出畫面
Value of integral is 1.7197
Real value of integral is 1.7183
Error tolerance is 0.001432
...Program finished with exit code 0
Press ENTER to exit console.
訂閱:
張貼留言 (Atom)
WOKWI LED + MQTT Node-Red SQLite
WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...
-
python pip 不是内部或外部命令 -- 解決方法 要安裝 Pyqt5 1. 首先,開啟命令提示字元。 2. 輸入 pip3 install pyqt5 好像不能執行 ! ! 錯誤顯示 : ‘ pip3 ’ 不是內部或外部命令、可執行的程式或批...
-
課程講義 下載 11/20 1) PPT 下載 + 程式下載 http://www.mediafire.com/file/cru4py7e8pptfda/106%E5%8B%A4%E7%9B%8A2-1.rar 11/27 2) PPT 下載...
-
• 認 識 PreFix、InFix、PostFix PreFix(前序式):* + 1 2 + 3 4 InFix(中序式): (1+2)*(3+4) PostFix(後序式):1 2 + 3 4 + * 後 序式的運算 例如: 運算時由 後序式的...
沒有留言:
張貼留言