Anna Collins
Anna Collins

Reputation: 83

Using a For Loop to find a sequences expression [1/1+1/2+1/3...1/1000]

I am needing assistance for an assignment. I am needing to use python to figure out how to create a "for Loop" that will do the following:

Series 1/1+1/2+1/3+1/4+...+1/1000 (which is expressed as 1000. ∑ n=1. 1 n ≈. 7.49)

I am needing the program to loop through all of them, printing each number out. Example:

998 7.483469855949342

999 7.48447086055343

1000 7.485470860550343

The basic what I currently got is

for x in range(1, 1000):

I don't know why but I just struggling to get this equation to work in my head. Any help would be greatly appreciated.

Upvotes: 1

Views: 489

Answers (3)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

itertools are your best friend. The proposed answers is correct but would be slow for big data. If I were you I would do:

import itertools

a = map(lambda x:1/x,range(1,1001))

#print(list(itertools.accumulate(a)))

for i, j in enumerate(1,itertools.accumulate(a)):
    print(i,j)

Explaination: lambda x:1/x creates on-fly function that would transform n to 1/n. map maps that function to the range of value starting from 1 to 1000. I then pass this to accumulating 1/1+1/2..... ;)

Upvotes: 1

Biswadip Mandal
Biswadip Mandal

Reputation: 544

Keep in mind that python2 will return 0 for 1/x and your sum will lead to 1 at the end. For getting float output(i.e. 0.25 for 1/4) one of the numbers have to be converted to float(either 1 or either x). Hence, the right way would be

sum = 0
for x in range(1, 1001):
    sum += (float(1)/x)
    print(sum, x)

Upvotes: 0

MaJoR
MaJoR

Reputation: 1044

You are going in the right direction. Before the for loop you would require a sum variable, where you would store the value of the summation of 1/x.

You can do that in a similar way:

sum = 0
for x in range(1, 1001):
    sum += (1/x)
    print(sum, x)

Here, I have initialized the sum variable to 0. After that, I iterate x over the values of [1, 1000] (both included). I find 1/x and add it to the sum. Next, I print the values, as you wanted.

NOTE: range(x, y) method gives you a range from x to y-1

Upvotes: 4

Related Questions