简体   繁体   中英

Calculating Napier constant (e) using recursion

I am attempting to approximate the value of e (~2.7)

Defined by this, for each nth term

对于每个第n个术语,由此定义

using a recursive function in python.

So far I have gotten this,

def NapierConstant(runs):
    return 2 + 1/contfrac(1, 2, runs)

def contfrac(v1, v2, limit):
    if v1 == limit:
        return (v1/v2)
    else:
        return v1+(v1/contfrac(v1+1, v2+1, limit))

print(NapierConstant(2))

this should output 2.72727 here, but instead I get 2.4, and the error margin get's worse for each following step. I have googled, and I can't manage to figure out how to set up the function recursively so that it outputs the expected values.

def get_e(lim):
    return 2 + 1/r(1, lim)

def r(v1, lim):
    if v1 == lim:
        return v1 + v1/(v1+1)
    else:
        return v1 + v1/(r(v1+1, lim))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM