Getting wrong output for this equation. Can someone review my code?
from math import cos
from math import sin
from math import pi
a0 = int(input("a0:"))
b0 = int(input("b0:"))
N = int(input("N:"))
L = int(input("L:"))
X = int(input("X:"))
n = 0
an = a0
bn = b0
y=0
for i in range(N):
an = an + 10 # since our first value would An = A0 +10 , we could just loop the values by adding 10 to it
bn = bn * 10
y= an * cos((n*pi*X/(L))) + bn*(sin(n*pi*X/(L)))
print(y)
y= an * cos((n*pi*X/(L))) + bn*(sin(n*pi*X/(L)))
There's never any change in the n variable! Given that n starts (and remains) at 0, you always calculate
an * cos(0) + bn * sin(0) == an * 1 + bn * 0 == an
Furthermore you need to add the result to the y variable, not just assign it. And you need to prime the y variable with a0.
an = a0
bn = b0
c = 0
d = pi * X / L # precalculating for efficiency
y = a0
for i in range(N):
an = an + 10
bn = bn * 10
c = c + d
y = y + an * cos(c) + bn * sin(c)
print(y)
Related
I am trying to write a program about Simpson's Law.What I am trying to do is use as error as shown in this picture:
.
In the code i write the Ih is my f1 and Ih/2 is my f2.If the error doesnt happen then the steps get halved.
However I get this error
Traceback (most recent call last):
File "C:\Users\Egw\Desktop\Analysh\Askhsh1\example.py", line 22, in <module>
sim2 = simps(f2, x2)
File "C:\Users\Egw\Desktop\Analysh\Askhsh1\venv\lib\site-packages\scipy\integrate\_quadrature.py", line 436, in simps
return simpson(y, x=x, dx=dx, axis=axis, even=even)
File "C:\Users\Egw\Desktop\Analysh\Askhsh1\venv\lib\site-packages\scipy\integrate\_quadrature.py", line 542, in simpson
last_dx = x[slice1] - x[slice2]
IndexError: index -1 is out of bounds for axis 0 with size 0
Process finished with exit code 1
My code is
import numpy as np
from sympy import *
from scipy.integrate import simps
a = 0
b = np.pi * 2
N = 100
ra = 0.1 # ρα
R = 0.05
fa = 35 * (np.pi/180) # φα
za = 0.4
Q = 10**(-6)
k = 9 * 10**9
aa = sqrt(ra**2 + R**2 + za**2)
error = 5 * 10**(-9)
while True:
x1 = np.linspace(a, b, N)
f1 = 1 / ((aa ** 2 - 2 * ra * R * np.cos(x1 - fa)) ** (3 / 2))
sim1 = simps(f1, x1)
x2 = np.linspace(a, b, int(N/2))
f2 = 1 / ((aa ** 2 - 2 * ra * R * np.cos(x2 - fa)) ** (3 / 2))
sim2 = simps(f2, x2)
if abs(sim1 - sim2) < error:
break
else:
N = int(N/2)
print(sim1)
I wasnt expecting any error,and basically expecting to calculate correctly.
When you reduce the grid step by half h -> h/2, the number of grid steps in turn grows N -> 2 * N, so you have to make two changes in your code:
Define x2 to have twice as many elements as x1
x2 = np.linspace(a, b, 2 * N)
Update N to be twice it was on the previous iteration
N = 2 * N
The resulting code would be
import numpy as np
from sympy import *
from scipy.integrate import simps
a = 0
b = np.pi * 2
N = 100
ra = 0.1 # ρα
R = 0.05
fa = 35 * (np.pi/180) # φα
za = 0.4
Q = 10**(-6)
k = 9 * 10**9
aa = sqrt(ra**2 + R**2 + za**2)
error = 5 * 10**(-9)
while True:
x1 = np.linspace(a, b, N)
f1 = 1 / ((aa ** 2 - 2 * ra * R * np.cos(x1 - fa)) ** (3 / 2))
sim1 = simps(f1, x1)
x2 = np.linspace(a, b, 2 * N)
f2 = 1 / ((aa ** 2 - 2 * ra * R * np.cos(x2 - fa)) ** (3 / 2))
sim2 = simps(f2, x2)
if abs(sim1 - sim2) < error:
break
else:
N = 2 * N
print(sim1)
And this prints the value
87.9765411043221
with error consistent with the threshold
abs(sim1 - sim2) = 4.66441463231604e-9
#DmitriChubarov's solution is correct. However, your implementation is very inefficient: it does double the work it needs to. Also, simps is deprecated, you should be using proper exponential notation, and your function expression can be simplified. For an equivalent error-free algorithm that still doubles the input array length on each iteration but doesn't throw away the intermediate result,
import numpy as np
from scipy.integrate import simpson
a = 0
b = 2*np.pi
N = 100
ra = 0.1 # ρα
R = 0.05
fa = np.radians(35) # φα
za = 0.4
aa = np.linalg.norm((ra, R, za))
error = 5e-9
sim1 = np.nan
while True:
x = np.linspace(a, b, N)
f = (aa**2 - 2*ra*R*np.cos(x - fa))**-1.5
sim2 = simpson(f, x)
if np.abs(sim1 - sim2) < error:
break
sim1 = sim2
N *= 2
print(sim1)
When I modified your code by adding two lines to print(len(x1), len(f1)) and print(len(x2), len(f2)), I got these results:
Output:
length of x1 and f1: 100 100
length of x2 and f2: 50 50
length of x1 and f1: 50 50
length of x2 and f2: 25 25
length of x1 and f1: 25 25
length of x2 and f2: 12 12
length of x1 and f1: 12 12
length of x2 and f2: 6 6
length of x1 and f1: 6 6
length of x2 and f2: 3 3
length of x1 and f1: 3 3
length of x2 and f2: 1 1
length of x1 and f1: 1 1
length of x2 and f2: 0 0
as you can see the length decreases each loop because N decreases and ends with an empty list length of x2 and f2: 0 0 and this causes the error you have had. To fix the issue of 'the empty list' I suggest that you duplicate N; this means using N*2 instead of N/2.
This code I wrote in Sympy is running slow. I want to write this with symengine. How can I translate? I had some difficulty with the Solve commands. Can you help me ?
Edit: Here is my code:
import sympy as sy
import time
#import numpy as np
import math as mat
from sympy import Eq
testere_capi=197
dis_sayisi=78
ic_acisi = 16
sirt_acisi = 8
derinlik_carpani = 0.4
kucuk_daire_carpani = 0.25
buyuk_daire_carpani = 0.8
son_dogrunun_carpani = 0.06
tas_kalinligi = 2.0
T = ((testere_capi * mat.pi) / dis_sayisi) # hatve
H = T * derinlik_carpani # derinlik
x = sy.symbols("x")
y = sy.symbols("y")
D2 = sy.Eq(y, H)
a8 = 0
b8 = 0
m_d1 = mat.tan(mat.radians(90 - ic_acisi))
D1 = sy.Eq(y - b8, m_d1 * (x - a8))
S1 = sy.solve((D2, D1), (x, y))
a1 = S1[x]
b1 = S1[y]
b2 = T * kucuk_daire_carpani
a2 = b2 / mat.tan(mat.radians(90 - ic_acisi) / 2)
r1 = T * kucuk_daire_carpani
D3 = sy.Eq((x - a2) ** 2 + (y - b2) ** 2, r1 ** 2)
D1 = sy.expand(D1)
D3 = sy.expand(D3)
S7 = sy.solve((D1,D3),(x,y))
a7 = S7[0][0]
b7 = S7[0][1]
Hi I make some derivative Program on Python, but the result isn't same as what i expected,
This is the result as what i want to be :
f(x) = x^2 - 8x + 25
f'(x) = 2x -8
0 = 2x - 8
8 = 2x
4 = x
x = 4
i want x to be equal to 4
and here's the code :
import sympy as sp
from sympy import *
p = 8
m = 25
f = x**2 - p*x + m
f_prime = f.diff(x)
f = lambdify(x, f)
f_prime = lambdify(x, f_prime)
f_prime(2)
the result is -4
how to solve this problem?
Thankyou
You have to define x as a symbolic variable (otherwise code will not compile), lambdify f_prime and solve the equation f_prime(x) = 0
from sympy import *
p = 8
m = 25
x = symbols('x')
f = x**2 - p*x + m
f_prime = f.diff(x)
print (f_prime)
f_prime = lambdify(x, f_prime)
print(solve(f_prime(x))[0])
2*x - 8
4
Basically I need to create a vertical histogram that cascades downwards.
My code so far:
a = 1
b = 8
c = 6
d = 7
x = [a, b, c, d]
z = max(x)
print(z)
i = 0
while i < z:
i += 1
a -= 1
b -= 1
c -= 1
d -= 1
if a >= 0:
print("*".ljust(5), end="")
if b >= 0:
print("*".ljust(5), end="")
if c >= 0:
print("*".ljust(5), end="")
if d >= 0:
print("*".ljust(5))
output obtained:
* * * *
* * *
* * *
* * *
* * *
* * *
* *
*
Required output:
* * * *
* * *
* * *
* * *
* * *
* * *
* *
*
ps: I'm new to all this so please excuse my ignorance 😁
Your code is almost working as is, but the *s are shifting over between columns.
If I change the *s to be the variable they are for, your current output looks like this:
a b c d
b c d
b c d
b c d
b c d
b c d
b d
b
You just need to print some whitespace when your if conditions come up False. So each one becomes
if a >= 0:
print("*".ljust(5), end="")
else:
print(" ".ljust(5), end="")
I am having issues calculating a function, while the function itself is pretty straightforward.
I have the following dataframe:
import pandas as pd
import numpy as np
import math as m
from scipy.stats import norm
dff = pd.DataFrame({'SKU': ['001', '002', '003','004','005'],
'revenue_contribution_in_percentage': [0.2, 0.2, 0.3,0.1,0.2],
'BuyPrice' : [7.78,9.96,38.87,6.91,14.04],
'SellPrice' : [7.9725,12.25,43,7.1,19.6],
'margin' : [0.9725,2.2908,5.8305,0.2764,5.1948],
'Avg_per_week' : [71.95,75.65,105.7,85.95,66.1],
'StockOnHand' : [260,180,260,205,180],
'StockOnOrder': [0,0,0,0,0],
'Supplier' : ['ABC', 'ABC', 'ABC','ABC','ABC'],
'SupplierLeadTime': [12,12,12,12,12],
'cumul_value':[0.20,0.4,0.6,0.8,1],
'class_mention':['A','A','B','D','C'],
'std_week':[21.585,26.4775,21.14,31.802, 26.44],
'review_time' : [5,5,5,5,5],
'holding_cost': [0.35, 0.35, 0.35,0.35,0.35],
'aggregate_order_placement_cost': [1000, 1000,1000,1000,1000],
'periods' : [7,7,7,7,7]})
dff['holding_cost'] = 0.35
dff1 = dff.sort_values(['Supplier'])
df2 = pd.DataFrame(dff1)
df2['forecast_dts'] = 5
df2['sigma_rtlt'] = 0.5
i need passing some of this parameters into the function:
#
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ^ 2))
num = (a0 + a1 * z + a2 * z ^ 2 + a3 * z ^ 3)
den = (b0 + b1 * z + b2 * z ^ 2 + b3 * z ^ 3 + b4 * z ^ 4)
k = num / den
return k
but then calculating
calc = calc_invUnitNormalLossApprox()*df2['sigma_rtlt']
returns the error:
File "/usr/local/lib/python3.7/site-packages/pandas/core/ops/__init__.py", line 1280, in na_op
dtype=x.dtype, typ=type(y).__name__
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
At this point I am not sure what is going on there, especially because i know the formula itself is correct, I am assuming there is something wrong with my use of norm pdf and cdf but I couldnt figure it out.
Any help would be really appreciated.
I think with the ^ operator you are trying to do a bitwise XOR
I think you need to use the ** operator.
This code works
def calc():
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ** 2))
num = (a0 + a1 * z + a2 * z ** 2 + a3 * z ** 3)
den = (b0 + b1 * z + b2 * z ** 2 + b3 * z ** 3 + b4 * z ** 4)
k = num / den
return k
Not : I have change the ^ operator to **