segmentation fault in pi calculation (python)

后端 未结 2 734
粉色の甜心
粉色の甜心 2021-01-21 08:52
def pi(times):
    seq = []
    counter = 0
    for x in range(times):
        counter += 2
        seq.append(\"((%f**2)/(%f*%f))*\"%(float(counter), float(counter-1),          


        
相关标签:
2条回答
  • 2021-01-21 09:34

    You appear to have found a bug in eval where it can't handle insanely long expressions:

    >>> eval("1.0*"*10000+"1.0")
    1.0
    >>> eval("1.0*"*100000+"1.0")
    # segfault here
    

    I use the phrase "insanely long" advisedly though. Don't do it that way, calculate the pieces as you go. There is no reason to be using eval in this situation.

    0 讨论(0)
  • 2021-01-21 09:52

    Why use eval() at all?

    def pi(times):
        val = 1
        counter = 0
        for x in range(times) :
            counter += 2
            val *= float(counter)**2/(counter**2 - 1)
        return val * 2
    

    Does the exact same thing.

    0 讨论(0)
提交回复
热议问题