Bohrium
robot
新建

空间站广场

论文
Notebooks
比赛
课程
Apps
我的主页
我的Notebooks
我的知识库
我的足迹

我的工作空间

任务
节点
文件
数据集
镜像
项目
数据库
公开
2025 AI4S TEEN Cup Challenge Physics——Appendix 1_Differentiation
python
2025 AI4S TCC Ph
python2025 AI4S TCC Ph
Chichuan Ma
郑子杰 Zijie Zheng
更新于 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
代码
文本
python
2025 AI4S TCC Ph
python2025 AI4S TCC Ph
点个赞吧
{/**/}