<jupyter_start><jupyter_text>数值积分/Numerical Integration<jupyter_code>import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>矩形法<jupyter_code># 定义被积函数
def my_f(x):
    return 3*(x**2)

# 定义原函数
def my_F(x):
    return x**3

# 定义积分区间
a = 4
b = 8

# 使用原函数求解析解
def analytic_solution(F, a, b):
    return F(b)-F(a)
plt.figure(figsize=[9,9])

# 绘制函数曲线
x = np.arange(0, 10, 0.1)
y = my_f(x)
plt.plot(x,y) 

# 借用柱状图对矩形法进行可视化
X = np.arange(a, b, 0.4)
Y = my_f(X+(b-a)/len(X)*0.5)
plt.bar(X,height=Y,width=(b-a)/len(X),align='edge',edgecolor='lightgray')

plt.title('$\\int_{4}^{8} 3 x^2 dx$')
plt.grid()
plt.show()<jupyter_output><empty_output><jupyter_text>下面通过一个简单的例子来看看矩形法的具体实现。- 求下面这个定积分的值：    $\int_{4}^{8} 3 x^2 dx$- 因为我们知道被积函数的原函数就是：$F(x) = x^3$    - 所以我们可以使用牛顿布莱尼兹公式求出解析解: $\int_{4}^{8} 3 x^2 dx = 8^3 - 4^3$    - 用来检查我们的矩形法计算的误差<jupyter_code># 使用中点法(midpoint rule)，实现一个自定义的矩形法积分函数
def my_quad(func, a, b, n):
    step = (b-a)/n
    half = step*0.5
    
    sum_y = 0
    for i in range(n):
        x = a + i*step + half
        y = func(x)
        sum_y += y
    
    # 每个矩形的底边长度都为 step，高度为 y
    # result = (y_1+y_2+y_3+....+y_n)*step
    return sum_y*step
# 使用不同的函数来计算一下
analytic = analytic_solution(my_F, a, b)
print("analytic solution = ", analytic)

result,error = integrate.quad(my_f, a, b)
print("scipy quad.result = {result}, error = {error}".format(result=result,error=error))

my_result = my_quad(my_f, a, b, 10000)
print("my quad.result = {result}, error = {error}".format(result=my_result,error=analytic-my_result))<jupyter_output>analytic solution =  448
scipy quad.result = 448.0, error = 4.973799150320701e-12
my quad.result = 447.9999998400029, error = 1.5999711422409746e-07
{'fraction_non_alphanumeric': 0.17017643710870803, 'fraction_numerical': 0.05919180421172453, 'mean_word_length': 4.376146788990826, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '308182', 'license': 'MIT', 'n_tokens_mistral': 977, 'n_tokens_neox': 940, 'n_words': 144, 'path': 'docs/part-1/04-NumericalIntegration.ipynb', 'repo_name': 'neil3d/LearnPBR', 'size': '1757'}