954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Finding doubling time by generator and logarithm

By Tony Veijalainen on Apr 29th, 2011 12:24 am
import itertools
import math

# to use input Python3 style in Python2
try:
    input = raw_input
except:
    pass

# margin to consider floating point numbers equal
delta = 1E-6

#A program to determine how long it takes for an investment to double
def main():
    I=float(input("Enter annualized interest rate as a percent: "))/100.
    # with generator
    increase = 1+I
    time_to_double = next(n for n in itertools.count() if increase**n > 2)
    print('Time to double by generator is:', time_to_double)
    # exactly by logarithm
    print('Years to exactly double by logarithm: %.3f' % math.log(2, increase))
    assert increase ** math.log(2, increase) - 2 < delta
main()

That assert check should of course be:

assert abs(increase ** math.log(2, increase) - 2) < delta

ie taking absolute value, otherwise any negative value would pass.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: