将函数传递给pyplot时出错

时间:2014-09-07 07:24:16

标签: python python-2.7

我创建了一个使用蒙特卡罗方法计算pi的Python 2.7脚本。然后我尝试使用pyplot在半对数图上创建pi值的图。这是我的代码:

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)

我看过马修亚当斯在this post中的解释,但似乎无法理解这个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要将main创建的列表元组解压缩到单独的参数ax.scatter,然后再传递它们:

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

或使用“splat”unpack语法:

ax.scatter(*main())

另一个参数,带你到三,是实例方法的隐式第一个self参数。