Python Forum
forloop to compute sum by alternating from addition to subtraction
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
forloop to compute sum by alternating from addition to subtraction
#1
I am currently struggling on a way to compute a sum that changes its sign from addition to subtraction e.g. 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13. I am adivised to use a forloop statement to compute this sum. Could somebody please help me out and explain the lines of code. Thanks!
Reply
#2
You present this in a way that only needs a print statement in front of it. One line of code.
If a loop is required the data will be presented differently. Show us that and what you have tried,
than we can help.
Paul
menator01 likes this post
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
sign = 1
total = 0
for x in range(1, 1002, 2):
    total += sign/x
    sign = -sign
print(total)
Not much to explain.
Reply
#4
Example with operator, iterator.cycle and Fraction.
It's not the "better" way, just a different way to show up, what is Python able to do.
The better way is often lesser code and not more code.

import operator
from itertools import cycle

# Bonus: you can get the exact fraction instead of a float
from fractions import Fraction


def sum_fractions(iterations, fractions=False):
    # we start with total 1
    # if iterations == 0, then the int 1 is returned
    # if iterations > 0, then total will convert into a float
    # if fractions == True, then Fraction is used
    total = 1
    numerator = 1
    denominator = 3
    # isub and iadd replaces -= and +=
    # cycle cycle through this two operator functions
    op_cycle = cycle((operator.isub, operator.iadd))

    # we don't need the value from range
    # so assign it to the throw away name _
    for _ in range(iterations):
        # get the next operator function from op_cycle
        op_func = next(op_cycle)

        # Bonus, use Fraction to do the calculation
        # Keep in mind, that this is much slower, but
        # gives you exact results
        if fractions:
            current_value = Fraction(numerator, denominator)
        else:
            # without Fraction
            current_value = numerator / denominator

        # here the isub or iadd function is used
        # instead of -= or  += use here assignment
        total = op_func(total, current_value)

        # increment the denominator by 2
        denominator += 2

    return total
The benefit is, that you can do more than + and - operation.
You can extend the tuple of op_cycle to multiply, divide or do the modulo operation.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,032 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  Odd numpy error with subtraction DreamingInsanity 5 2,716 Jun-01-2020, 02:49 PM
Last Post: DreamingInsanity
  Basic subtraction error rix 4 3,407 Oct-11-2019, 06:43 AM
Last Post: buran
  addition for elements in lists of list ridgerunnersjw 3 3,077 Sep-15-2019, 07:11 AM
Last Post: perfringo
  multiplication by successive addition Zebrol 1 3,508 Sep-14-2019, 05:37 PM
Last Post: ichabod801
  Addition of 2 classes Naito 1 1,940 Feb-15-2019, 10:51 AM
Last Post: DeaD_EyE
  Python 2.7 Addition to dict is too slow VolanD 6 4,027 May-04-2018, 09:24 AM
Last Post: Gribouillis
  Trying to create a python exe for an addition problem with an odd variable Python_Newb 0 2,149 Nov-30-2017, 12:18 PM
Last Post: Python_Newb
  How to make a subtraction within a range of numbers? Alberto 3 10,092 May-08-2017, 09:13 PM
Last Post: ichabod801
  pdf sms alternating conversation style sdcaliber 4 5,172 Apr-20-2017, 05:20 AM
Last Post: sdcaliber

Forum Jump:

User Panel Messages

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