Add variables in an loop to a formula - python

I have a problem.
I am using a formula:
x = var1 * multiplier1 + var2 * multiplier2, etc.
I have 300 variables, so I want to loop through the variables and add them, but what I try doesn't work. I understand why it is not working, but I can't figure out how I have to do it correctly. This is my code:
multiplier = {}
count = 0
while (count != len(data[0])):
ri = np.random.randint(len(data))
point = data[ri]
x = point[count] * multiplier[count]
count += 1
It is not adding the variables to the formula, but it calculates it again. How can I make it work?

You seem to be missing a + sign.
Change x = point[count] * multiplier[count]
to x += point[count] * multiplier[count]
And declare x=0 before your loop.
Beware that nowhere in this code the multiplier dict is populated with values !
multiplier = {}
count = 0
x = 0
while (count != len(data[0])):
ri = np.random.randint(len(data))
point = data[ri]
x += int(point[count]) * multiplier[count]
count += 1

Related

McLaurin series for cosine

I want to make a cosine function that relies on the McLaurin expansion on cosine.. but it doesn't work: it should return me '-1.0..something' but it returns me another value, please can you guys help me??
code:
import math
def _cos(n:float,prec:int):
a = []
k = 0.0
for x in range(prec):
a.append(
((-1)**k)*((n**(2*k+1))/(2*k+1))
)
k+=1
z = 0
for x in a:
z+=x
return z
pi = math.pi
print(_cos(pi,200))
print(math.cos(pi))
As I can see you don't have the good formula.
((-1)**k)*((n**(2*k+1))/(2*k+1))
it's n**(2*n)
then you need to divide it by the factorial of 2n
4! = 4 * 3 * 2 * 1
2n! = 2n * 2n-1 * 2n-2 * 2n-3 ...
your formula of mac laurin is false: see maclaurin cosinus
in your loop, you do a mixture with the pow (x is the pow not k)
your correct code will be:
def _cos(n:float,prec:int):
a = []
for x in range(prec):
a.append(
((-1)**x)*((n**(2*x))/factorial(2*x))
)
z = 0
for x in a:
z+=x
return z
pi = 3.14159265359
print(_cos(pi,200))
print(math.cos(pi))
but if you do that with a precision of 200, you will be an overflow
try with 10 is already best.
i suggest you to use the precicion not from a number of iteration but from the difference between old value and new value like this :
def _cos(n:float,prec:float):
k = 0
cosine_x = 0.0
while True:
old = cosine_x + (pow(-1, k) * pow(n, 2 * k) / factorial(2 * k))
#print(old)
if 0 < abs(old - cosine_x) < prec:
return old
cosine_x = old
k += 1
pi = 3.14159265359
print(_cos(pi,0.000000000000001))
print(cos(pi))
You were not updating k, as you used x for the range and you were missing the factorial function in the division. Try with precison as 20, but 200 is too high.
Try the following code:
import math
def _cos(n:float,prec:int):
a = []
k = 0
for k in range(prec):
a.append(
((-1)**k) * ((n**(2*k))) /
math.factorial(2*k)
)
z = 0
for x in a:
z += x
return z

Problem doing multiplication tables with while function

I am a new programmer and this is my first question here so excuse me if its pretty easy.
M doing a multiplication table but each time it stops after the 1 and it doesnt increment the number
I am trying to do it with 2 while loops
nb = 1
i = 0
while nb<10 :
while i<=10 :
print(nb * i)
i+=1
nb+=1
with that code I only have the 1 multiplication table then the program stops
Reset variable inside loop. Variable i reaches its max value after the first iteration of inner loop, which we need to set back to 0 for the next iteration to work:
nb = 1
while nb < 10 :
i = 0
while i <= 10 :
print(nb * i)
i += 1
nb += 1
You can do the same using for, which in my opinion is more readable and you don't need to worry about incrementing/resetting variables:
for x in range(1, 10):
for y in range(11):
print(x * y)

Numerical method in python- can't spot the problem?

I am writing this numerical method formula of trapezium rule for double integrals.
Note that hx = (b-a)/nx, hy = (d-c)/ny to get the interval widths and xj = a+hxj and yi = c+hyi
A few problems in your code:
First yes your indentation here is off (but I assume it's from not copying it across well since this would lead to an error rather than a wrong value). In the future make sure the indentation in your question corresponds to what you have at on your own computer before posting...
Then a term should be added within a for if and only if it's in the corresponding sum... Here you put everything within the double for loop which corresponds to having all the terms in the double sum.
Finally range(1,n) already stops at n-1 only so you want to remove those -1 in the ranges.
In the end:
def double_integral(f,a,b,c,d,nx,ny):
hx = (b-a)/nx
hy = (d-c)/ny
first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))
i_sum = 0
for i in range(1,ny):
i_sum += f(a,c+i*hy)+f(b, c+i*hy)
j_sum = 0
for j in range(1,nx):
j_sum += f(a+j*hx,c)+f(a+j*hx,d)
ij_sum = 0
for i in range(1,ny):
for j in range(1,nx):
ij_sum += f(a+j*hx,c+i*hy)
integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy
return integral
def t(x,y):
return x*(y**(2))
print(double_integral(t,0,2,0,1,10,10))
0.6700000000000003
You'll get closer to 2/3 by choosing numbers of steps larger than 10...
And you can be more pythonic by using sum comprehension:
def double_integral(f,a,b,c,d,nx,ny):
hx = (b-a)/nx
hy = (d-c)/ny
first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))
i_sum = sum(f(a,c+i*hy)+f(b, c+i*hy) for i in range (1,ny))
j_sum = sum(f(a+j*hx,c)+f(a+j*hx,d) for j in range(1,nx))
ij_sum = sum(f(a+j*hx,c+i*hy) for i in range (1,ny) for j in range(1,nx))
integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy
return integral

python, print intermediate values while loop

I am sorry if this is very basic, I am new to programming.
When I run my code, only the last value is printed.
How can I modify my code, so that the entire list in range N is displayed, using a while loop?
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)
You didn't indent the x.append. So the code is not inside the loop and only the last value is appended to x. Correct would be:
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)
Your indenting is slightly off, but beyond that you can simply add the print statement to the while loop
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(xn)
print(x)
You need to put the x.append(xn) inside the while loop. Otherwise only the last xn will be appended to x.
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)

Python for-loop counter error

I am attempting to script a short code to figure out the number of days it takes to reach a given principal in the bank due to daily interest. Using my code below does not yield any errors when run in IDLE, but the counter returns 0. Any ideas what I missed?
def main():
# irrelevant code elided by msw, Bal, Int and Tar are numeric
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
print counter
I'm not sure what you're getting at with this loop:
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
range(0) is an empty list, so the loop won't execute at all.
counter + 1 simply calculates one more than counter, it won't increment counter, you probably mean counter += 1
There's nothing in the loop that changes at each iteration, so if you ever get into it, it will be an infinite loop.
I believe the formula to calculate final balance with interest is:
Final = Principal * ( 1 + interest ) ** interest_period
Assuming I got this correct, then you can find out how many interest periods it will take by:
def how_long(start_money, interest_rate, final_money):
day = 0
money = start_money
while True:
if money >= final_money:
break
day += 1
money = start_money * (1 + interest_rate)**day
return day, money
In [5]: def test():
...: for i in range(0):
...: return '1'
...:
...:
In [6]: x = test()
In [7]: print x
------> print(x)
None
See the return value is 'None'.
I don't know what are you trying to do. But The basic mistake is the Argument of range(x) function. The range(0) always return empty list.
That's because you put range(0) which is an empty loop. Perhaps you could consider a while loop?
Your loop for i in range(0) doesn't actually execute. range(0) returns an empty list [] which will skip the body of your for loop.
Please explain what you think this does? Please update your question with an English-language explanation of how many times you think this look will work.
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
Hint. The answer is zero. The question is "why?" and "what were you trying to do?"
You have been told the three or more problems with your code. If there's no particular reason to use a loop, it's better calculated with a formula:
future_value = present_value * (1 + interest_rate_per_period) ** number_of periods
or, for short,
f = p * (1 + i) ** n
f / p = (1 + i) ** n
log(f / p) = n * log(1 + i)
n = log(f / p) / log(i + i)
Example: I have $5000; how many years will it take to grow to $10000 at 10% per annum?
>>> from math import log
>>> f = 10000.0
>>> p = 5000.0
>>> i = 0.1
>>> n = log(f / p) / log(1 + i)
>>> n
7.272540897341713
>>>

Categories