用矩形法积分近似运算(1)sin(x),下限为0.0,上限为pir/2。 (2)exp(x),下限为0.0,上限为1.0。 (3)4.0/(1+x×x),基类(integer)成员数据包括积分上下限b和a,分区数n,步长step= n b−a ,积分值result。 定义积分函数integerate()为虚函数,它只显示提示信息。 派生的矩形法类(rectangle)重定义integerate(),下限为0.0,上限为1.0。
时间: 2023-06-12 08:04:31 浏览: 49
下面是题目要求的三个部分的代码实现:
1. sin(x)的矩形法积分近似运算:
```python
import math
class integral:
def __init__(self, a, b, n):
self.a = a
self.b = b
self.n = n
self.step = (b - a) / n
self.result = 0.0
def integrate(self):
print("This is the base class and cannot be used to integrate.")
class rectangle(integral):
def integrate(self):
self.result = 0.0
for i in range(self.n):
x = self.a + i * self.step + self.step / 2.0
self.result += math.sin(x) * self.step
print("The approximate value of sin(x) integral from 0 to pi/2 is:", self.result)
# 测试代码
r = rectangle(0.0, math.pi/2, 100)
r.integrate()
```
2. exp(x)的矩形法积分近似运算:
```python
import math
class integral:
def __init__(self, a, b, n):
self.a = a
self.b = b
self.n = n
self.step = (b - a) / n
self.result = 0.0
def integrate(self):
print("This is the base class and cannot be used to integrate.")
class rectangle(integral):
def integrate(self):
self.result = 0.0
for i in range(self.n):
x = self.a + i * self.step + self.step / 2.0
self.result += math.exp(x) * self.step
print("The approximate value of exp(x) integral from 0 to 1 is:", self.result)
# 测试代码
r = rectangle(0.0, 1.0, 100)
r.integrate()
```
3. 4.0/(1+x^2)的矩形法积分近似运算:
```python
import math
class integral:
def __init__(self, a, b, n):
self.a = a
self.b = b
self.n = n
self.step = (b - a) / n
self.result = 0.0
def integrate(self):
print("This is the base class and cannot be used to integrate.")
class rectangle(integral):
def integrate(self):
self.result = 0.0
for i in range(self.n):
x = self.a + i * self.step + self.step / 2.0
self.result += 4.0 / (1 + x * x) * self.step
print("The approximate value of 4/(1+x^2) integral from 0 to 1 is:", self.result)
# 测试代码
r = rectangle(0.0, 1.0, 100)
r.integrate()
```