将函数传递给pyplot时出错

0 投票
1 回答
517 浏览
提问于 2025-04-20 06:08

我写了一个Python 2.7的脚本,用蒙特卡罗方法来计算圆周率(pi)。然后,我想用pyplot画出圆周率的值在半对数图上的变化。以下是我的代码:

from numpy.random import rand, seed
import matplotlib.pyplot as plt

## Initialize the random number generator with seed value of 1
seed(1)

## Set the dimensions of the square and circle and the total number of cycles
sq_side = 1.0
radius = 1.0
cycles = 1000000
total_area = sq_side**2

## The main function
def main():
    # Initialize a few variables and the X,Y lists for the graph
    i = 0
    N = 0
    Y = []
    X = []
    while not N == cycles:
        # Generate random numbers and test if they are in the circle
        x,y = rand(2, 1)
        if x**2 + y**2 <= 1.0:
            i += 1
        # Calculate pi on each cycle
        quarter_circle_area = total_area * i / cycles
        calculated_pi = 4 * quarter_circle_area / radius**2
        # Add the value of pi and the current cycle number to the X,Y lists
        Y.append(calculated_pi)
        X.append(N)
        N += 1
    return X, Y

## Plot the values of pi on a logarithmic scale x-axis
ax = plt.subplot(111)
ax.set_xscale('log')
ax.set_xlim(0, 1e6)
ax.set_ylim(-4, 4)
ax.scatter(main())

plt.show()

可是,我遇到了一个错误信息:

Traceback (most recent call last):
  File "C:/Users/jonathan/PycharmProjects/MonteCarlo-3.4/pi_simple.py", line 45, in <module>
    ax.scatter(main())
TypeError: scatter() takes at least 3 arguments (2 given)

我看过Matthew Adams在这篇帖子里的解释,但我还是搞不懂这个问题。希望能得到一些帮助。

1 个回答

1

你需要把由 main 创建的列表元组拆开,变成 单独的参数 传给 ax.scatter,可以在传递之前这样做:

x, y = main()
ax.scatter(x, y)

或者使用“拆包”语法:

ax.scatter(*main())

另外一个参数,变成三个的原因,是因为实例方法的第一个参数 self 是隐式的。

撰写回答