Python Forum

Full Version: Sum Series w/ Fractions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Oct-10-2016, 10:47 PM)EwH006 Wrote: [ -> ]Anyway I'm looking to do the same thing with the code I gave but I need to use the following fractions, in which I don't know how apply to the syntax of while or for loops: 1/3 , 3/5, 5/7, 7/9, 9/11, 11/13, +..... all the way to 97/99 = 45.12445030305

It won't let me use floating point numbers in the for loop for sure.

You can use floating point numbers in a loop, but you can't use them in the range function. In this case you don't need to worry about that. Note that all those fractions are in the same format: n/(n + 2). So you need to loop over the n's (1 to 97, going up 2 each time), then add n/(n + 2) to your total each time through the loop.
Thanks for all the help.

'''Programmer: Eric Hanlon
Class: CIS120
Section: 402
Program Name: Exercise05_27
Description: This program will run a sum series of fractions
'''

sum = 0
n = 1

for n in range(1, 98, 2):       # for loop with max cap at 97
    sum = sum + (n / (n+2))
    print(sum)
Some comments on that solution...

You don't need n = 1. It can (and should) be safely dropped.

An expression of the form s = s + 1 can be replaced with s += 1.

sum is built-in, so is discouraged from being used as a variable. "result" or something might be preferable.

Speaking of sum(), you can use a generator comprehension with it
print(sum(n / (n + 2) for n in range(1, 98, 2)))
Don't worry about this last one if it feels advanced.
Pages: 1 2