리만 합계를 사용하여 근사값을 근사화하고 Python에서 matplotlib를 사용하여 그래프를 그릴 수있는 프로그램을 작성했습니다. x 축의 위와 아래에 같은 면적을 가진 함수의 경우, 결과 영역은 0이되어야하지만, 프로그램은 아주 작은 숫자를 출력합니다.파이썬 리먼 합계는 양수 및 음수 영역에 대해 0을 반환하지 않습니다.
다음 코드는 홀수 함수 f (x) = x^3을 -1에서 1로 그래프로 표시하므로 영역은 0이어야합니다. 대신 내 코드는 1.68065561477562 e^-15로 근사합니다.
이 문제의 원인은 무엇입니까? delta_x, x 또는 y의 반올림 오류입니까? 저는 값을 0으로 반올림 할 수 있다는 것을 압니다. 그러나 이것을 해결할 다른 문제가 있는지 궁금합니다.
나는 delta_x에 대해 Decimal.decimal 클래스를 사용해 보았지만 훨씬 작은 숫자가 있습니다.
파이썬 코드 :
import matplotlib.pyplot as plt
import numpy as np
# Approximates and graphs integral using Riemann Sum
# example function: f(x) = x^3
def f_x(x):
return x**3
# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000
# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a)/n
x = np.arange(a, b+delta_x, delta_x)
y = [f_x(i) for i in x]
area = sum(y) * delta_x
# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()
예를 들어 홀수 개의 하위 구간 만 사용한다면 충분히 재미있을 것입니다. 왼쪽 리만의 합을 '1'에서 '1 + delta_x'로 바꾸는 것은'-1-delta_x/2 '를'1 + delta_x/2'로 바꾸어서 대칭을 유지합니다. – eugenhu