2019年4月16日 星期二

例題4-1梯行法(Trapezoidal method) 計算 exp(x) 在[0 , 1] 的定積分

<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.       

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...