新建
2025 AI4S TEEN Cup Challenge Physics——Appendix 1_Differentiation




更新于 2024-11-29
推荐镜像 :ai4s-cup:0.3.1
推荐机型 :c2_m4_cpu
赞
[3]
import torch
import numpy as np
# 定义函数
# define function
def f(x):
return x**3 + 2*x**2 + 3*x
# 微分的数值计算
# Numerical calculation of derivative
x_numpy = np.array([2.0])
h = 1e-7
def numerical_derivative(f, x, h):
return (f(x + h) - f(x - h)) / (2 * h)
df_dx_numpy_manual = numerical_derivative(f, x_numpy, h)
print("Numerical Derivative:")
print(f"df/dx at x = {x_numpy[0]} is {df_dx_numpy_manual[0]}")
# 导数的解析计算
# Analytical calculation of derivative
def df(x):
return 3*x**2 + 4*x + 3
x_theory = 2.0
print("Theoretical Derivative:")
print(f"df/dx at x = {x_theory} is {df(x_theory)}")
# PyTorch自动微分
# PyTorch automatic differentiation
x_torch = torch.tensor([2.0], requires_grad=True)
y_torch = f(x_torch)
dy_dx = torch.autograd.grad(y_torch, x_torch, grad_outputs=torch.ones_like(y_torch),
create_graph=True)[0]
print("PyTorch Automatic Derivative:")
print(f"df/dx at x = {x_torch.item()} is {dy_dx.item()}")
Numerical Derivative: df/dx at x = 2.0 is 22.999999984563146 Theoretical Derivative: df/dx at x = 2.0 is 23.0 PyTorch Automatic Derivative: df/dx at x = 2.0 is 23.0
代码
文本
点个赞吧