Python Forum
Sum Series w/ Fractions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum Series w/ Fractions
#11
(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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
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)
Reply
#13
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Periodic Fractions with Fraction or float_to_ratio? TimeMen 3 2,940 May-20-2018, 03:48 PM
Last Post: ljmetzger

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020