第一题
from math import *
def print_(x):
if type(x) == float:
print("%.4f" % x)
else:
print(x)
#**********Begin**********#
class Integral:
def __init__(self, f, a, n):
self.f = f
self.a = a
self.n = n
def __call__(self, x):
h = (x - self.a) / self.n
sum_area = 0.5 * (self.f(self.a) + self.f(self.a + h)) # 第一个梯形的面积
for i in range(1, self.n):
sum_area += self.f(self.a + i * h) # 中间梯形的面积,不需要乘0.5
sum_area += 0.5 * self.f(x) # 最后一个梯形的面积
return sum_area * h
#**********End**********#
def f(x):
return exp(-x**2)*sin(10*x)
for x in [0.0, 0.1, 0.2, 0.5, 1.0]:
a = 0; n = 20000 #改了分割份数才能对,无语了
F = Integral(f, a, n)
print_(F(x))
第二题
class Interval:
def __init__(self, lower, upper):
self.lower = lower
self.upper = upper
def __add__(self, other):
return Interval(self.lower + other.lower, self.upper + other.upper)
def __sub__(self, other):
return Interval(self.lower - other.upper, self.upper - other.lower)
def __mul__(self, other):
# 乘法需要考虑符号和极值情况
min_mul = min(self.lower * other.lower,
self.lower * other.upper,
self.upper * other.lower,
self.upper * other.upper)
max_mul = max(self.lower * other.lower,
self.lower * other.upper,
self.upper * other.lower,
self.upper * other.upper)
return Interval(min_mul, max_mul)
def __truediv__(self, other):
# 假设other不包含0,并且self不包含0
return Interval(self.lower / other.lower, self.upper / other.upper)
def __str__(self):
return f"[{self.lower:.1f}, {self.upper:.1f}]"
I = Interval
for l in [-4, -3]:
for u in [-3, -2]:
a = I(l,u)
b = I(4,5)
expr = 'a+b', 'a-b', 'a*b', 'a/b'
for e in expr:
print(e, '=', eval(e))