Home > Back-end >  How do I get the total of a sequence of rational numbers?
How do I get the total of a sequence of rational numbers?

Time:12-17

I have a list of fractional numbers to get the total of them. I'm not allowed to use fraction module other than for, while loops. Can someone help me, please? I'm studying by myself.

Here is my question :

Write a loop that calculates the total of the following series of numbers:

1/30 2/29 3/28 ... 30/1

Update

Here is the code I wrote:

starting_number = 1 / 30
ending_number = 30/1
total = 0.0
for number in range(starting_number, ending_number, starting_number   1 / ending_number -1):
    total  = number

print(total)

Here is the output:

Traceback (most recent call last):
  File "C:\Users\jimsrc\Desktop\repo\New folder\test2.py", line 4, in <module>
    for number in range(starting_number, ending_number, starting_number   1 / ending_number -1):
TypeError: 'float' object cannot be interpreted as an integer

Process finished with exit code 1

CodePudding user response:

I think you are attempting to make your range() call much more complicated than it needs to be (or that it supports).

Let's take your idea, but move the work inside the loop:

n = 30
total = 0
for i in range(1, n 1):
    total  = i/(n 1-i) 
print(total)

That gives us 93.84460105853213 which is going to be close to the value you seek. It may or may not be the correct answer depending on how you expect float to behave. See: Is floating point math broken?

Once you understand what is going on here it is not a huge leap to the simplification suggested by @wjandrea.

n = 30
total = sum(i/(n 1-i) for i in range(1, n 1))
print(total)

also giving you: 93.84460105853213

  • Related