零散地

2024-04-27 03:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在函数y=2x周围画一条散乱点的线。与正常函数(即f(x))相比,这些点的随机偏差应该在-0.5到0.5之间:

def f(x):
    return 2 * x

def g(x):
    return f(x) - np.random.uniform(-0.5, 0.5)

x = np.linspace(0, 5, 51)
y = f(x)
y2 = g(x)

# plot
plt.plot(t, y, 'b-')
plt.plot(t, y, 'ro')
plt.show()

当然,y2现在是一条散乱的线,所有的点都有相同的偏差,因为所有的点的随机数都是相同的。现在我想知道怎样才能使每个点都有一个随机偏差(那么我怎样才能对每个点单独执行一个操作)。提前谢谢!你知道吗


Tags: 函数returnroplotdefshownpplt
1条回答
网友
1楼 · 发布于 2024-04-27 03:30:12

是:将size=(51,)(或者更好,使用x数组的形状)传递到np.random.uniform()以从均匀分布中提取那么多样本:

import numpy as np
import matplotlib.pyplot as plt
def f(x):
    return 2 * x

def g(x):
    return f(x) - np.random.uniform(-0.5, 0.5, size=x.shape)

x = np.linspace(0, 5, 51)
y = f(x)
y2 = g(x)

# plot
plt.plot(x, y, 'b-')
plt.plot(x, y2, 'ro')
plt.show()

enter image description here

相关问题 更多 >