例題4-1 計算 exp(x) 在[0 , 1]的定積分
'''
import math
def f(x) :
return math.exp(x)
def computeT(a , b , n) :
h = (b - a) / n
T = 0.0
for i in range (1 , n ):
T += f(a + i * h) # //1 <= k <= n - 1
return (h * 0.5 * ( f(a) + 2 * T + f(b) ) )
n = 10 #//區間等分數
a = 0.0
b = 1.0 #//上下限
print("answer = {%10.6f}\n" %( computeT(a, b, n) ) )
print("exp(x) 在[0, 1]的定積分={%10.6f}\n" %(math.exp(1)-math.exp(0) ) )
print("誤差值={%10.6f}\n" % ( abs (computeT(a, b, n) - (math.exp(1)-math.exp(0) ) ) ) )
'''
/*
本實驗用梯形求積公式求sinx在[1, 2]的定積分。
*/
#include <stdio.h>
#include <math.h>
double f(double x){
return sin(x);
}
double computeT(double a, double b, int n){
double h = (b - a) / n, T = 0;
for(int i = 1; i < n; i++) T += f(a + i * h); //1 <= k <= n - 1
return h * (f(a) + 2 * T + f(b)) / 2;
}
int main(){
int n = 8; //區間等分數
double a = 1, b = 2; //上下限
printf("answer = %f\n", computeT(a, b, n));
return 0;
}
'''
輸出畫面
======= RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/EX4-1-0.py ===========
answer = { 1.719713}
exp(x) 在[0, 1]的定積分={ 1.718282}
誤差值={ 0.001432}
>>>
沒有留言:
張貼留言