r/PythonLearning • u/Leviathans_ • 1d ago
Help Request help for a programing assignment
I need to write a program that will calculate the sum of the first n of 1 + 1/2 + 1/4 + ... = lim (n -> ∞) Σ 1/2^k =2 starting at k=0 to n.
Teacher said we could use Σ 1/2^k = 2 - 1/2^(n-1) starting at k=0 to n-1
We have to write it using a loop.
I went back through my notes and figured I needed to use a «for» loop.
My teacher starts all of his programs with def, but when I try to look up more infos online I struggle to find others who are using it.
So, here's what I've tried
def estimate_serie (nb_term) :
sum = 0
for term in range (1, nb_term + 1) :
sum=sum + 1/(2 ** term)
return sum
print (estimate_serie(5))
print (estimate_serie(8))
print (estimate_serie(12))it gave me
0.5
0.5
0.5
Btw I am learning this in french so I might not have translated all of it correctly. I've also only been learning for a month, so if my mistakes seem dumb that might explain why.
4
u/Due-Mortgage-6854 1d ago
Your return sum must be outside the FOR Loop and your for term in range(1, nb_term + 1) must start from zero giving : for term in range(nb_term + 1)
1
u/Leviathans_ 1d ago
I did the changes you proposed and tried with 1,2,3 instead of 5,8,12 for simpler numbers.
I got 1.5 instead of 1 for 1
1.75 instead of 1.5 for 2
And the same for 3
Sadly, the power went out 😭 so I will be working on this later, but thank you for the help2
u/Due-Mortgage-6854 1d ago
ahh im really sorry its
for term in range(nb_term)not (nb_term+1). I typed in a hurry😅
2
u/Dazzling_Music_2411 17h ago
I ran it (correcting for your zero mistake) and it runs fine. I think you must have a mistake in your indentations.
When you post code, can you please format it properly, otherwise no one can tell what is going on.
1
u/Naive_Programmer_232 19h ago
hmm when I run your code on my side I get
0.96875
0.99609375
0.999755859375your code has a small error. consider this equation
k
∑ 1/(2^i) = 2 - 1/(2^k)
i=0if k=0 to account for the zeroth term, then the sum should be:
k=0 k
∑ 1/(2^i) = 2 - 1/(2^k)
i=0
= 2 - 1/(2^0)
= 2 - 1/1
= 2 - 1
= 1but in your code you have this
def estimate_serie(nb_term):
sum=0
for term in range(1,nb_term+1):
sum=sum+1/(2**term)
return sum
# trying nb_term=0
estimate_serie(0)
# 0this happens because the range becomes range(1,1) and the loop will not execute, so in this case sum=0 which is incorrect, it should be 1.
to get around this edge case you can do one of two things to account for zeroth term:
keep
range(1,nb_term+1)but setsum=1.0use
range(nb_term)and initializesum=0.0
both of these will calculate exactly nb_term amount of terms.
now one thing to note, conventionally, you want to be careful with using built-in function names as variables. the reason for this is python will overwrite the reference to the original function it is pointing to. so by doing sum=0, since sum is a built-in function, it is no longer representing that function, instead it's value now is 0. in this case it isn't as big as an issue since sum is overwritten locally, it won't change the global definition,
anyhow, I ran your function then tested it against two other rewrites i made for the first 50 terms and a random set of 50 terms and it works:
# your function (edited s instead sum; and range(nb_term))
def f1(nb_term: int) -> float:
"""
to make it work for the first nb_term terms
- range(nb_term) gives range [0,nb_term-1] (width=nb_term)
"""
s=0.0
for term in range(nb_term):
s=s+1/(2**term)
return s
# my function
def f2(k: int) -> float:
"""
recall:
k
∑ 1/(2**i) = 1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^(k-1))
i=0
i 0 1 2 3 k-1
count 1 2 3 4 k
to make it work for k terms (zeroth inclusive)
- range(k) gives range [0,k-1] (width=k)
"""
return sum(1/(2**i) for i in range(k))
# math rule function
def f3(k: int) -> float:
"""
recall:
k
∑ 1/(2**i) = 2 - 1/(2^k) for k+1 terms [0,k] (width=k+1)
i=0
so then,
k-1
∑ 1/(2**i) = 2 - 1/(2^(k-1)) for k terms [0,k-1] (width=k)
i=0
to make it work for the first k terms (zeroth inclusive)
- use k-1 for exponent
"""
return 2-1/(2**(k-1))
# test function (compares output of all three for set of inputs)
# since floating comparison can get messy with precision,
# a good exercise to see is compare 0.1+0.2==0.3 for example,
# here I use math.isclose() for that reason as comparison measure for 3 floats
import math
def comp3(f1_result: float, f2_result: float, f3_result: float) -> bool:
return (
math.isclose(f1_result,f2_result) and
math.isclose(f2_result,f3_result) and
math.isclose(f1_result,f3_result)
)
# *args is any number of positional arguments, args is a tuple[int] in this case
def test(*args: int) -> None:
ellipsis=False
for i,arg in enumerate(args,start=1):
# get results of each function
f1_r=f1(arg)
f2_r=f2(arg)
f3_r=f3(arg)
# print only first 5 checks and last 3 checks
if i<6 or i>47:
print(f"f1({arg})={f1_r}=" + \
f"f2({arg})={f2_r}=" + \
f"f3({arg})={f3_r}")
# print ... once in between
elif not ellipsis:
print("...")
ellipsis=True
# compare results of all functions -> if True -> no exiting error
# if False -> exit w/error showing test case that failed
assert comp3(f1_r,f2_r,f3_r), f"broke on {arg}::test failed"
# all args successfully passed
print("\nall tests passed")
# test first 50 terms [0,49] across all function solutions
test(*range(50))
f1(0)=0.0=f2(0)=0=f3(0)=0.0
f1(1)=1.0=f2(1)=1.0=f3(1)=1.0
f1(2)=1.5=f2(2)=1.5=f3(2)=1.5
f1(3)=1.75=f2(3)=1.75=f3(3)=1.75
f1(4)=1.875=f2(4)=1.875=f3(4)=1.875
...
f1(47)=1.9999999999999858=f2(47)=1.9999999999999858=f3(47)=1.9999999999999858
f1(48)=1.999999999999993=f2(48)=1.999999999999993=f3(48)=1.999999999999993
f1(49)=1.9999999999999964=f2(49)=1.9999999999999964=f3(49)=1.9999999999999964
all tests passed
# test with random 50 unique values [0,100] across all function solutions
import random
test(*random.sample(range(101),k=50))
f1(14)=1.9998779296875=f2(14)=1.9998779296875=f3(14)=1.9998779296875
f1(46)=1.9999999999999716=f2(46)=1.9999999999999716=f3(46)=1.9999999999999716
f1(93)=2.0=f2(93)=2.0=f3(93)=2.0
f1(2)=1.5=f2(2)=1.5=f3(2)=1.5
f1(29)=1.9999999962747097=f2(29)=1.9999999962747097=f3(29)=1.9999999962747097
...
f1(73)=2.0=f2(73)=2.0=f3(73)=2.0
f1(39)=1.999999999996362=f2(39)=1.999999999996362=f3(39)=1.999999999996362
f1(10)=1.998046875=f2(10)=1.998046875=f3(10)=1.998046875
all tests passedanyway good luck! hope this helps on the code side!!
extra: math learning about why f3 solution works (what your teacher provided):
we know that for k+1 terms this is true,
k
∑ 1/(2^i) = 2 - 1/(2^k) [k+1 terms]
i=0and in f3 we saw how by limiting to k-1 we got the following for k terms:
k-1
∑ 1/(2^i) = 2 - 1/(2^(k-1)) [k terms]
i=0In order to verify however that the first statement is actually true, we can use a proof technique known as mathematical induction:
game plan:
the goal with this proof is to show the same rule for the first k+1 terms
k
∑ 1/(2^i) = 2 - 1/(2^k) [k+1 terms]
i=0
also holds for k+2 terms,
k+1
∑ 1/(2^i) = 2 - 1/(2^(k+1)) [k+2 terms]
i=0
to do this we need to examine the base case and an inductive hypothesis.
----
base case: (referencing k+1 term definition)
let k=0
then, left: ∑1/(2^i) = 1/(2^0) = 1
then, right: 2 - 1/(2^k) = 2 - 1/(2^0) = 2 - 1 = 1
see left = right
inductive hypothesis: (assuming k+1 def is true, show k+2 def is true too)
assume the provided is true for arbitrary non-negative integer k
k
∑ 1/(2^i) = 2 - 1/(2^k)
i=0
we want to show this holds for k+1 [k+2 terms]
that is,
k+1
∑ 1/(2^i) = 2 - 1/(2^(k+1))
i=0
so,
k+1 k
∑ 1/(2^i) = ∑ 1/(2^i) + 1/(2^(k+1)) split the sum
i=0 i=0
= [2 - 1/(2^k)] + 1/(2^(k+1))
ψ see 2^(k+1) is 2(2^k),
= 2 - 1/(2^k) + 1/(2(2^k)) 2(2^k) ~ 2^(k+1)
= 2/2[ 2 - 1/(2^k) + 1/(2(2^k)) ] multiply all by 2/2
= 4/2 - 2/2^(k+1) + 2/2(2^(k+1)) distribute/sub using ψ
= 2 - 2/2^(k+1) + 1/2^(k+1) simplify
= 2 - 1/(2^(k+1)) combine like terms
k+1
∴ ∑ 1/(2^i) = 2 - 1/(2^(k+1)),
i=0
we can now generalize this for any non-negative integers k and n where
0 <= k <= n < ∞1
u/Repulsive-Song-1594 7h ago
Man i have the same problem but simpler and i cannot understand how to use function and lists inside a loop to calculate something if you found a way to learn that through a video hit me up
0
•
u/Sea-Ad7805 1d ago edited 1d ago
Run program above by clicking Memory Graph Web Debugger and see its state change step by step.
It gives output:
Oh IC, you indented (put white-space in front of)
return sumtoo much like in this code which gives the output you describe.Indentation is very important in python, as with this indentation the
return sumis part of the loop, so the loop will run only once and then return. The Memory Graph Web Debugger visualization makes it clear what going wrong, use it for debugging.