N=5
For(rate=0.05, rate <= 0.15, rate = rate +0.05)
For(principle=1000, principle <= 1500, principle=principle + 1000)
simple = principle * (1 + rate * N) #Where N is the number of years
compound = principle * (1 + rate) ^ N
print simple + " " + compound
End For
End For
views:
151answers:
5
+1
A:
Try this:
N = 5
rate = .05
while rate <= .15:
principle = 1000
while principle <= 1500:
simple = principle * (1 + rate * N)
compound = principle * (1 + rate) ** N
print "%s %s" % (simple, compound)
principle += 1000
rate += .05
Edit: fixed the code. xrange apparently doesn't take floats :(
This doesn't work, since range/xrange take in integers. Or at least, they do on Python 2.6.
Brian
2010-04-13 20:21:38
You're correct. Thanks for the tip.
2010-04-13 20:26:54
A:
You can't use xrange/range directly since they require integer arguments.
The way to do this is with a nice generator expression and a while loop, I think:
# if N is the number of years, say so in the variable name
numYears = 5
# start with 0.05, then 0.10, then 0.15 (the +1 is since xrange uses <, not <=)
# just increase the second xrange() argument to try more rates
rates = (0.05 * x for x in xrange(1, 3+1))
for rate in rates:
# you're adding 1000 and then stopping at 1500... so this only executes once!
principle = 1000
while principle <= 1500:
simple = principle * (1 + rate * numYears)
# ** is the power operator in Python
compound = principle * (1 + rate) ** numYears
# Python conveniently enters spaces for you
print simple, compound
# now update the loop variable
principle += 1000
Daniel G
2010-04-13 20:28:52
+1
A:
It should be about this:
N=5
rates = [i/100.0 for i in xrange(5,16,5)]
for r in rates:
for p in xrange(1000, 1501, 1000):
s = p*(1+r*N)
c = p*(1+r)**N
print s, c
KillianDS
2010-04-13 20:31:12
A:
You can make it work with minimal changes to the pseudocode
N=5
for rate in range(5, 15+1, 5): #+1 needed to include last term
rate *= 0.01
for principle in range(1000, 1500+1, 1000):
simple = principle * (1 + rate * N)
compound = principle * (1 + rate)** N
print str(simple) + " " + str(compound)
joaquin
2010-04-13 21:00:19
A:
Pretty similar to KillianDS's but uses a generator expression. Saves you a couple of kB of memory (not that it matters).
N = 5
for rate in (i / 100.0 for i in xrange(5, 15 + 1, 5)):
for principle in xrange(1000, 1500 + 1, 1000):
simple = principle * (1 + rate * N)
compound = principle * (1 + rate) ** N
print "%s %s" % (simple, compound)
kaloyan
2010-04-13 21:49:06