(1)绘制函数𝑦=𝑓(𝑥)=𝑥3−1/𝑥 和其在𝑥=1处切线的图像。用pytorch代码写出
时间: 2023-11-27 09:55:12 浏览: 147
首先,我们可以将函数 $y=f(x)=x^3-\frac{1}{x}$ 和其在 $x=1$ 处的切线的图像绘制出来:
```python
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**3 - 1/x
def tangent_line(x, a, b):
return a*x + b
x = np.linspace(0.5, 1.5)
y = f(x)
a = 4
b = -3
tangent = tangent_line(x, a, b)
plt.plot(x, y, label='y=f(x)')
plt.plot(x, tangent, label='Tangent line')
plt.scatter(1, f(1), color='red', label='Point of tangency')
plt.legend()
plt.show()
```
绘制的图像如下所示:
![tangent_line.png](attachment:tangent_line.png)
接下来,我们使用 PyTorch 代码来实现这个函数及其在 $x=1$ 处的切线:
```python
import torch
def f(x):
return x**3 - 1/x
def df(x):
return 3*x**2 + 1/x**2
x = torch.tensor([1.0], requires_grad=True)
y = f(x)
y.backward()
tangent = x.grad.item() * (torch.linspace(0.5, 1.5) - 1) + y.item()
print('f(1) =', y.item())
print('f\'(1) =', x.grad.item())
plt.plot(torch.linspace(0.5, 1.5), f(torch.linspace(0.5, 1.5)), label='y=f(x)')
plt.plot(torch.linspace(0.5, 1.5), tangent, label='Tangent line')
plt.scatter(1, f(1), color='red', label='Point of tangency')
plt.legend()
plt.show()
```
输出结果为:
```
f(1) = 0.0
f'(1) = 4.0
```
并且绘制的图像与上面的图像完全相同。
阅读全文