如何对每次k迭代获得的X的所有值求和?
print('Enter value for N between 1 and 50:') #User inputs number for N
N=int(input())
k=1
if N < 1:
print('N must be between 1 and 50')
while k <= N:
if N < 50:
x=(1/(2**k)) #Value X is calculated for each value of N
print('x=', x)
k=k + 1
else:
print('N must be between 1 and 50')
break
答案 0 :(得分:0)
只需创建一个名为sum
的新变量,该变量从0开始。每当您拥有x
的新值时,就将x
的值累加到其中。
print('Enter value for N between 1 and 50:') #User inputs number for N
N=int(input())
k=1
sum=0
if N < 1 or N > 50:
print('N must be between 1 and 50')
exit()
while k <= N:
x=(1/(2**k)) #Value X is calculated for each value of N
sum=sum+x
print('x=', x)
k=k + 1
print("Sum = ", sum)
请注意,我还在循环之前将N
的验证转移了,因为您只需要检查一次即可。
答案 1 :(得分:0)
您可以尝试变得更加精确吗?
是否要像当前一样在每次迭代中显示x
,并在末尾显示一个全局计数,将所有x
相加?
在这种情况下,您可以引入一个额外的变量,如下所示
print('Enter value for N between 1 and 50:') #User inputs number for N
N=int(input())
k=1
if N < 1:
print('N must be between 1 and 50')
total_count = 0 # new variable
while k <= N:
if N < 50:
x=(1/(2**k)) #Value X is calculated for each value of N
print('x=', x)
total_count += x # this updates the total count
k=k + 1
else:
print('N must be between 1 and 50')
break
答案 2 :(得分:0)
即使在多达50次的操作中(通常)不需要,我也会使用numpy来向量化我的答案。
import numpy as np
N=int(input('Enter value for N between 1 and 50: '))
if N < 1 or N > 50:
print('N must be between 1 and 50')
else:
x = 1/(2**np.arange(1, N+1, dtype=float))
print(x) # in case you want to know the value at each "iteration"
sum = np.sum(x)
print(sum)
答案 3 :(得分:0)
为此做一个证明,但是1 - (1/2**N)
也会给你答案。