Not sure about the syntax of the output I am receving. Any help would be appreciated.
Here is my code:
import numpy
def g(): #generate random complex values
return numpy.random.random(1) + numpy.random.random(1) *1j
p = numpy.poly1d(numpy.squeeze([g(),g(),g()])) # test function p
pprime = numpy.polyder(p) #derivative of p
print 'Our p(x) is {} '. format(p)
print('\n') # new line
print'Our pprime(x) is {} '. format(pprime) #apply newtons method to p
print('\n') # new line
#apply newtons method to p
def root_newton ( f, df, tolerance = 1.0e-6):
dx = 2 * tolerance
x=0
while dx > tolerance:
x1 = x - f(x)/df(x)
dx = abs (x - x1)
x = x1
return x
print('Our first root is at {}'.format(root_newton(p,pprime)))
print('\n') # new line
Here's the output:
Our p(x) is 2
(0.6957 + 0.683j) x + (0.3198 + 0.5655j) x + (0.9578 + 0.1899j)
Our pprime(x) is
(1.391 + 1.366j) x + (0.3198 + 0.5655j)
Our first root is at (0.00925817978737+0.830966156841j)
The correct roots are [-0.64968928-1.01513333j 0.00925818+0.83096616j]
What does the 2 above the second component in my first line outputted mean? I can't find anything similar to my question online. I am guessing it may mean the x component is squared but I'm not sure? This is python 3 by the way.
The 2 is the exponent on the first x, misaligned because you put text before it on the same line.
If we take your output:
Our p(x) is 2
(0.6957 + 0.683j) x + (0.3198 + 0.5655j) x + (0.9578 + 0.1899j)
and remove the text you prepended:
2
(0.6957 + 0.683j) x + (0.3198 + 0.5655j) x + (0.9578 + 0.1899j)
the intended meaning of the 2 becomes clearer.
Related
I am new here. I want to write a neat litte program to check the solutions of my exam preparations as my professor didnt provide any. For a non- linear differential equation f I want to find the 1st Taylor polynomial. Therefore I take the derivative of f in respect to every variable.
Now my problem:
I have to calculate the value of each derivative for a certain given point. How can I do that for such complex expressions that are just stored in a variable and not explicitly known, as they are calculated?
This is what i do now, without evaluating:
f = input('Enter function: ')
fy1 = diff(f,y1)
fy = diff(f,y)
fu2 = diff(f,u2)
fu1 = diff(f,u1)
fu = diff(f,u)
I tried this function as I hoped it would recognize the variables in f automatically:
def calculate(f,y1,y,u2,u1,u):
return f
...
fy1 = calculate(diff(f,y1),0,-1,0,0,-4)
fy = calculate(diff(f,y),0,-1,0,0,-4)
fu2 = calculate(diff(f,u2),0,-1,0,0,-4)
fu1 = calculate(diff(f,u1),0,-1,0,0,-4)
fu = calculate(diff(f,u),0,-1,0,0,-4)
Edit:
I tried out something else:
For f= -5yy1+4*y-u (y1 is the derivative of y)
fy1 is the derivative of f in respect to y1:
fy1= diff(f, y1)
fy1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print("{}".format(fy1))
But subs() didnt substitute any values as the output was the following:
-5*y
I guess it has something to so with the variables being defined as sympy symbols?
y1 = symbols('y1')
y = symbols('y')
u2 = symbols('u2')
u1 = symbols('u1')
u = symbols('u')
But I need that for the sympy diff()-function
My solution for now is almost what I wrote in my first edit. What I didnt realize was that the substitution is not permanent and I had to store the solution in an extra variable.
Here is the complete program. I am open for suggestions to improve it an all aspects.
from sympy import diff, symbols
again = True
while(again):
y1 = symbols('y1')
y = symbols('y')
u2 = symbols('u2')
u1 = symbols('u1')
u = symbols('u')
f = input('Enter function: ')
fy1= diff(f, y1)
res_fy1 = fy1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print("{}".format(res_fy1))
fy= diff(f, y)
res_fy = fy.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu2= diff(f, u2)
res_fu2 = fu2.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu1= diff(f, u1)
res_fu1 = fu1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu= diff(f, u)
res_fu = fu.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print('delta_y2 + (' + str(res_fy1) + ')*delta_y1 + (' + str(res_fy) + ')*delta_y + (' + str(res_fu2) + ')*delta_u2 + (' + str(res_fu1) + ')*delta_u1 + (' + str(res_fu) + ')*delta_u')
wrongInput = True
while (wrongInput):
i = input('Another function? [y/n] ')
if (i == 'n'):
again = False
wrongInput = False
elif (i == 'y'):
wrongInput = False
else:
print('Wrong Input!')
I need to write a program that, when provided inputs by the user, will create a polynomial based on the position of the input order.
For example, if the user input: 1 2 3
The polynomial should be printed x^2 + (2.0)x^1 + 3 and this answer should be in float form. How do I do that?
This is what I have done so far
def get_expression(x1):
x1=""
power = len(x1) - 1
for i in range(len(x1)):
if x1[i] < 0:
x1 += str(x1[i])
else:
x1 += "+" + str(x1[i])
if x1[i] == 0:
continue
if power == 1:
x1 += "x"
elif power == 0:
x1 = x1
else:
x1 += "x" + str(power)
power = power - 1
if sum(x1)==0:
return float(0)
return x1
The code should satisfy the code below and give results correctly in the form: -4.5x - 5 & 2x^2 - 3
p1=[-4.5,-5.0]
print(get_expression(p1))
p2=[2.0,0.0,-3.0]
print(get_expression(p2))
Please help me and advise how I could correct my code and get an answer in float form.
You could build the string naively and then make it look nicer with string replacements:
def poly(*C):
result = "+".join(f" {c}x^{-p} " for p,c in enumerate(C,1-len(C)) if c)
result = result.replace("+ -","- ") # subtract for negative coefficient
result = result.replace("^1 "," ") # implicit x^1
result = result.replace("x^0","") # implicit x^0
result = result.replace(" 1x"," x").replace("-1x","-x") # implicit 1x
return result.strip()
for example: poly(-1,0,3,-1,5)
result = ' -1x^4 + 3x^2 + -1x^1 + 5x^0 ' # naive build (skips zero coeff.)
result = ' -1x^4 + 3x^2 - 1x^1 + 5x^0 ' # subtract for negative coefficient
result = ' -1x^4 + 3x^2 - 1x + 5x^0 ' # implicit x^1
result = ' -1x^4 + 3x^2 - 1x + 5 ' # implicit x^0
result = ' -x^4 + 3x^2 - x + 5 ' # implicit 1x
return '-x^4 + 3x^2 - x + 5' # strip extra space for return
output:
print(poly(1,2,3)) # x^2 + 2x + 3
print(poly(-4.5,-5)) # -4.5x - 5
print(poly(2,0,-3)) # 2x^2 - 3
print(poly(-1,0,-1.5,5,0,-32)) # -x^5 - 1.5x^3 + 5x^2 - 32
print(poly("a","b","-c")) # ax^2 + bx - c
Sort of follow your logic and re-write your code, FYI.
def get_expresultsion(x1):
result = "" # use another variable instead of x1
power = len(x1) - 1
for i in range(len(x1)):
if x1[i] < 0:
result += str(x1[i])
elif x1[i] == 0:
# put this into the same IF logic since this part is checking x1[i] as well
power = power - 1
continue
else:
result += "+" + str(x1[i])
# check power then
if power == 1:
result += "x"
elif power == 0:
pass
else:
# add "^"
result += "x^" + str(power)
power = power - 1
if sum(x1) == 0:
return float(0)
return result
At the time of viewing your question, I couldn't understand the logic you were following so I wrote it from scratch as simple as I can.
def get_expression(coefficient_list):
power = 0
expression = "" #Our final result (instead of x1)
if len(coefficient_list) == 1: #For the case having just the constant
return(coefficient_list[0])
elif len(coefficient_list) > 1:
for coefficient in reversed(coefficient_list): #We reverse the list
if power == 0: #Dealing with constant
expression += str(coefficient)
else: #Here it puts the coeff and power together and adds to the left side of expression
expression = f"({coefficient})x^{power} + " + expression
power += 1
return expression
Python 2 how to do this.Print the value of the series x = 1 + 1/2 + 1/3 + 1/4 + … + 1/n for the user’s input of n.
Here you go:
n = int( input() ) # reading user input
x = 0
for i in range(1, n + 1): # adding 1/1 + 1/2 + 1/3 + ... + 1/n
x += 1.0/i
print(x) # => outputs : 2.283333333333333
There may be a Harmonic Series function in Python packages like math or numpy, or some similar way to deal with it, especially if you need high precision at large values of n. Otherwise, you could just do this:
>>> n = 5
>>> print(sum(1.0/i for i in range(1,n+1)))
2.28333333333
Note that the "1.0" is important for Python 2.x so that it knows to deal with floats. Otherwise things get rounded along the way:
>>> print(sum(1/i for i in range(1,n+1)))
1
I'm fairly new to this but will try and be as clear as possible.
Essentially I have 5 different lists of lists. 4 are imported from txt files and the 5th is a merger of the 4. Each inner list contains a value at index position 3. My objective is to maximize the sum by picking appropriately.
I also have a couple constraints:
The sum of the values at index 6 position can't exceed 50000
I pick 2 items from set C, 3 from set W, 2 from set D, 1 from set G, and 1 from set U (the combined) and I can't pick the same item for each set. Ie. each pick in W has to be different.
My code is below. I'm having trouble in that the optimizer just spits out my initial list of picks. Looking at the data though, I know for sure there are better solutions. I read that the issue may be related to late binding but I'm not sure if that's right and if it is, not sure how to update to fix error either. Appreciate any help. Thanks!
Read: Scipy.optimize.minimize SLSQP with linear constraints fails
import numpy as np
from scipy.optimize import minimize
C = open('C.txt','r').read().splitlines()
W = open('W.txt','r').read().splitlines()
D = open('D.txt','r').read().splitlines()
G = open('G.txt','r').read().splitlines()
def splitdata(file):
for index,line in enumerate(file):
file[index] = line.split('\t')
return(file)
def objective(x, sign=-1.0):
x = list(map(int, x))
pos = 3
Cvalue = float(C[x[0]][pos]) + float(C[x[1]][pos])
Wvalue = float(W[x[2]][pos]) + float(W[x[3]][pos]) + float(W[x[4]][pos])
Dvalue = float(D[x[5]][pos]) + float(D[x[6]][pos])
Gvalue = float(G[x[7]][pos])
Uvalue = float(U[x[8]][pos])
grand_value = sign*(Cvalue + Wvalue + Dvalue + Gvalue + Uvalue)
#print(grand_value)
return grand_value
def constraint_cost(x):
x = list(map(int, x))
pos = 6
Ccost = int(C[x[0]][pos]) + int(C[x[1]][pos])
Wcost = int(W[x[2]][pos]) + int(W[x[3]][pos]) + int(W[x[4]][pos])
Dcost = int(D[x[5]][pos]) + int(D[x[6]][pos])
Gcost = int(G[x[7]][pos])
Ucost = int(U[x[8]][pos])
grand_cost = 50000 - (Ccost + Wcost + Dcost + Gcost + Ucost)
#print(grand_cost)
return grand_cost
def constraint_C(x):
if x[0] == x[1]:
return 0
else:
return 1
def constraint_W(x):
if x[2] == x[3] or x[2] == x[4] or x[3] == x[4]:
return 0
else:
return 1
def constraint_D(x):
if x[5] == init[6]:
return 0
else:
return 1
con1 = {'type':'ineq','fun':constraint_cost}
con2 = {'type':'ineq','fun':constraint_C}
con3 = {'type':'ineq','fun':constraint_W}
con4 = {'type':'ineq','fun':constraint_D}
con = [con1, con2, con3, con4]
c0 = [0,1]
w0 = [0,1,2]
d0 = [0,1]
g0 = [0]
u0 = [0]
init = c0+w0+d0+g0+u0
C = splitdata(C)
W = splitdata(W)
D = splitdata(D)
G = splitdata(G)
U = C + W + D + G
sol = minimize(objective, init, method='SLSQP',constraints=con)
print(sol)
I want to apply the following function to multiple instances of a, b, c but it seems I can't apply this function to a list. The goal is to compute a few inequalities and finally plug them into a new z = ax + bx equation in order to find the lowest or highest ordered pair.
This is a cleaner code that omits the use of lists:
xMin,yMin = 0,0
a,b,c = 2,-3,12
enter code here
def FindVar(object):
x = (-b*yMin)/a + c/a
y = (-a*xMin)/b + c/b
print '(', FindVar.x, ',', yMin, ')'
print '(', xMin, ',', FindVar.y, ')'
This is a longer code that uses lists a bit more sloppily:
xMin = 0
yMin = 0
def i1():
a,b,c = 2,-3,12
#Create and append l1
global l1
l1 = []
l1.extend((a,b,c))
#Find X,Y
y = (-a*xMin)/b + (c/b)
x = (-b*yMin)/a + c/a
#Add to list
pair = []
pair.append((xMin,y))
pair.append((x,yMin))
print '%sx + %sy = %s' % (a,b,c)
print 'RETURNS'
print pair[0], z1
print pair[1], z2
def i2():
a,b,c = 1,1,5
#Create and append l2
global l2
l2 = []
l2.extend((a,b,c))
#Find X,Y
y = (-a*xMin)/b + c/b
x = (-b*yMin)/a + c/a
#Add to list
pair = []
pair.append((xMin,y))
pair.append((x,yMin))
print '%sx + %sy = %s' % (a,b,c)
print 'RETURNS'
print pair[0], z1
print pair[1], z2
So with the second bit of code I end up with 4 list items, each of which should be applied to a final equation, z = ax + by where a and b are independent from other functions.
EDIT: The purpose is to take an equation like "z = 2x + 7y" and subject it to the rules:
2x - 3y ≤ 12,
x + y ≤ 5,
3x + 4y ≥ 24,
x ≥ 0,
y ≥ 0.
I take these equations and put them into a list so that a,b,c = [2,-3,12],[1,1,5],[3,4,24] (where a = 2,1,3, b = -3,1,4, and c = 12,5,24). Then I can find (x,y) according to each of the three instances and plug each of those ordered pairs into my initial "z = 2x + 7y". The point of all of this is to take sets of data and find which set is the most efficient.
z1 and z2 were used in a prior version of the code to apply the "z=2x+7y" to the first and second ordered pairs of the first equation.
EDIT 2:
This is the much cleaner code I came up with.
xMin = 0
yMin = 0
a = [10,11,1]
b = [7,-8,1]
c = [200,63,42]
def findxy(a,b,c):
#Finds x,y for ax+by=c
x = (-b*yMin)/a + c/a
y = (-a*xMin)/b + c/b
#The results, followed by the z function "z = 15x + 15y"
if x >= xMin:
print '(%s, %s)' % (x,yMin), 15 * x + 15 * yMin
if y >= yMin:
print '(%s, %s)' % (xMin,y), 15 * xMin + 15 * y
map(findxy,a,b,c)
Results in
(20, 0) 300
(0, 28) 420
(5, 0) 75
(42, 0) 630
(0, 42) 630
Thanks!
To apply a function to each object in a list you can use the built in function map.
The list you pass to map can consist of primitives, class instances, tuples or lists.