Xx = np.linspace(-rangex, rangex, grid_number) Xx[Xx < 1] = 0.1 ValueError: assignment destination is read-only
时间: 2023-12-04 17:05:50 浏览: 82
这个错误提示表明你尝试修改一个只读的数组。在这种情况下,`Xx`是由`np.linspace`函数创建的一个NumPy数组,它是只读的。因此,你不能直接修改这个数组。要解决这个问题,你需要将数组复制到一个新的变量中,在新变量上进行修改。例如,你可以使用以下代码来创建一个可写的数组:
```
Xx = np.linspace(-rangex, rangex, grid_number)
Xx_copy = Xx.copy() # 复制可写数组
Xx_copy[Xx_copy < 1] = 0.1 # 在可写数组上进行修改
```
这样,在新变量`Xx_copy`上进行修改,就可以避免修改只读数组`Xx`而导致的错误。
相关问题
给出一组数据x=[-1,-0.96,-0.62,0.1,0.4,1],y=[-1,-0.1512,0.386,0.4802,0.8838,1],分别使用2~5次多项式对其进行多项式拟合,绘制出拟合曲线。
以下为Python代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 数据
x = np.array([-1, -0.96, -0.62, 0.1, 0.4, 1])
y = np.array([-1, -0.1512, 0.386, 0.4802, 0.8838, 1])
# 多项式拟合
f2 = np.polyfit(x, y, 2)
f3 = np.polyfit(x, y, 3)
f4 = np.polyfit(x, y, 4)
f5 = np.polyfit(x, y, 5)
# 绘制拟合曲线
xx = np.linspace(-1, 1, 1000)
y2 = np.polyval(f2, xx)
y3 = np.polyval(f3, xx)
y4 = np.polyval(f4, xx)
y5 = np.polyval(f5, xx)
plt.plot(x, y, 'o', label='data')
plt.plot(xx, y2, label='2nd degree')
plt.plot(xx, y3, label='3rd degree')
plt.plot(xx, y4, label='4th degree')
plt.plot(xx, y5, label='5th degree')
plt.legend()
plt.show()
```
运行结果如下图所示:

使用scipy.optimize.root找到sin x - 1/x在0.1到20的所有根
好的,让我来帮你解决这个问题。以下是使用scipy.optimize.root找到sin x - 1/x在0.1到20的所有根的代码:
```python
import numpy as np
from scipy.optimize import root
def f(x):
return np.sin(x) - 1/x
x0 = np.linspace(0.1, 20, 200)
roots = []
for i in range(len(x0)-1):
sol = root(f, [x0[i], x0[i+1]])
if sol.success:
roots.append(sol.x[0])
print("The roots of sin x - 1/x in the range of 0.1 to 20 are:")
print(roots)
```
希望这可以帮助你找到所有的根。
阅读全文
相关推荐
















