I'd like to write a program in Python where user define a deegre of polynomial and coefficients (a,b,c). When program create a polynomial expression with this data I'd like to use it like function because I need this to other operations. How can i get it? For example when I have polynomial= x^n+a^n-1+b^n-2+c^-3 I'd like to use it in polynomial(x) to calculate value.
Now the creating polynomial method looks:
def polynomial(n,a,b,c):
return a*x**n+b*x**3-c*x
class Polynomial:
def __init__(self, coeficents, degrees=None):
if degrees = None:
self.degree = list(reversed(range(len(coeficents))))
else:
self.degree = degrees
self.coeficents = coeficents
def __call__(self, x):
print(self.coeficents)
print(self.degree)
return sum([self.coeficents[i]*x**self.degree[i] for i in range(len(self.coeficents))])
p = Polynomial([1,2,4],[10,2,0])
print(p(2))
This will compute the polynomial x^10 + 2x^2 + 4 at x = 2. It should be very clear how to use with your example.
The best strategy is not to pass in n, but you will need to pass in x. You should instead pass the coefficients in as a list. You don't need to pass in n as it is calculated from the length of the list.
def poly(coefs, x):
result=0
N=len(coefs)
n=0
while N-n>0:
result+=coefs[n]*(x**(N-n-1))
n+=1
return result
So if you want to calculate, for example x^2 + 3x -5 where x=5, you would use this line:
print(poly([1,3,-5], 5))
Related
Premise:
Suppose I have a variable x and two function f(x) and g(x)
such that when f(x) has the ability to change the value of x (maybe it wants to keep track on how many times f(x) has been called) and g(x) doesn't want to change the value of x at any cost.
Now if i was choose x as an integer, I can accomplish g(x) and if x is a list, I can accomplish f(x).
Question:
But what if I want to accomplish both of them in the same program?
What should I do then?.
If its not possible, then doesn't this severely handicap python wrt other languages.
Note:
Basically my question is motivated by finding the drawbacks of not having pointers in python as in other language like C++, the above task can easily be implemented by choosing the *x instead of x.
If all you need to do is change the value of a variable that you pass to f, you can simply return the new value:
def f(x):
return x + 1
x = 30
x = f(x)
# x is now 31
If there is already another value you need to return from f, you can return a tuple and unpack the return value to multiple variables:
def f(x):
return 46, x + 1
x = 30
y, x = f(x)
# x is now 31
In C++, the use of pointers that you bring up compensates for the fact that it's relatively difficult to return multiple values from a function. In Python, while we're still technically returning one value, it's much easier to create tuples and unpack them.
You could make your own class:
`class some_class():
self._value = 0
self._access_counter = 0
def update_value(self):
<your code here>
def get_value_by_ref(self):
self._access_counter += 1
return self._value
`
How to create a functinon in Python such that for example:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def x(x):
return x
lni=[]
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (x(x)-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
I think I need it to return the function such that the formula variable is a function by x in its own right and so later i can call upon it in the fashion
formula(10)=output
Set the results of a function call equal to your desired variable.
def f(x):
"A function that changes nothing"
return x
a = f(5) # same as a = 5
To avoid confusion, I recommend that you don't give functions the same name as their arguments, (i.e., don't do def x(x): ...).
If you want formula to be a function, then declare it as one, after which the correct syntax would be output = formula(10).
formula(10) is instance of a function and hence only has a value not a variable name to assign to.
A good way to write above code will be:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def y(x):
return x
def formula_calc(X):
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (X-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
return formula
# now formula is a function of x. X can itself be a function.
print(formula(y(7))
# this will print value of formula at 7 as x(7) is 7.
I have a function f(x,a) where 'x' is a variable and 'a' is a parameter. I want creat a function F(x) that is a sum of f(x,a) for a range of parameter 'a', for instance:
F(x) = f(x,a1) + f(x,a2) + f(x,a3) + ... + f(x,aN) but how I have a large range for 'a' (a=[a1,a2,a3,...,aN]) I want to write a program for this but I don't now how. For instance:
import numpy as np
# Black-Body radiation equation: 'x' is related to frequency and 'a' is related to temperature
def f(x,a):
return x**3/(np.exp(a*x) - 1)
# range for parameter a:
a = [1000,2000,3000,4000,5000,6000]
# Superposition of spectrum
def F(x):
return f(x,a[0]) + f(x,a[1]) + f(x,a[2]) + f(x,a[3]) + f(x,a[4]) + f(x,a[5])
The last line for function F(x) isn't very smart, so I tried make a loop in the above sum with sum() function
def F(x):
spectrum = []
for i in a:
spectrum = sum(f(x,i))
return spectrum
But as I don't have much experience with Python this doesn't work and I got the error:
import matplotlib.pyplot as plt
x = np.linspace(0,100,500)
plt.plot(x,F(x))
plt.show()
# ValueError: x and y must have same first dimension, but have shapes (500,) and (1,)
Does anyone know how to do this? thank you very much
From what i understand, this should do the job:
def F(x):
return sum(f(x, _a) for _a in a)
The thing I do in the sum() function is called list comprehension, feel free to look this Python feature if you are interested by Python coding: it is very powerful.
I was wondering how I could manipulate a function to take a new argument in Python without modifying original formula.
For example, how would I take square function and make another function like multiply square using square function as a model:
Original Function:
def square(x):
result = (x*x)
return(result)
New Function, takes a new argument "y":
def multSquare(x,y):
result = y*square(x)
return(result)
I tried using decorators but I can't seem to have it working
def addArg(tarFun):
def wrapArg(y, *args, **kwargs):
result=tarFun(*args, **kwargs) * y
return result
return wrapArg
def square(x):
result = (x*x)
return(result)
multSquare = addArg(square)
print(square(2)) # This should be 4
print(multSquare(2,3)) # This should be 12
This doesn't work because I don't how to inject y.
In the end, I want to make a function that takes all the arguments of the original function plus one more argument.
Thanks everybody!
If you pay attention to the order of your arguments, what's happening is that you are squaring 3 and multiplying it by 2. This is because your function wrapArg uses the first argument (2) as the number you are multiplying with and the second (3) as the number you are squaring.
multSquare(3, 2) will give the result you want.
In additional to what busybear said you could just swap the parameters around
def addArg(fun):
def wrapArg(x, y):
result = fun(x) * y
return result
return wrapArg
def square(x):
result = (x * x)
return(result)
multSquare = addArg(square)
print(square(2)) # This should be 4
print(multSquare(2, 3)) # This should be 12
or additionally just use optional arguments
def square(x, y = None):
sq = x*x
if y:
sq *= y
return sq
For context, I am essentially using a numerical integrator that takes in a set of differential equations defined as functions. A large set of these functions follow a regular pattern and I would like to define them in a loop (or whatever is the most suitable way). For example;
#system coordinates
s = [y1,y2]
#system equations
def e1(s):
x1 = s[1]**2 + 1
return x1
def e2(s):
x1 = s[2]**2 + 2
return x1
#equations of motion
eom = [e1,e2]
Not all of the functions will follow the exact pattern, for those that do though ideally I need something like,
def en(s)
x1 = s[n]**2 + n
return x1
where it is possible to iterate over a range of 'n' values. Thanks for any advice.
Why not simply use a second parameter in your function like so:
def en(s, n)
x1 = s[n]**2 + n
return x1
result = []
for i in range(100): # 100 is just for illustration purposes..
result[0] = en(s, i) # you do not have to store them in a list. just an example
I would use partial, wich bind values to functions arguments:
import functools
def e1(s, n, v1, v2):
x1 = s[n]**v1 + v2
return x1
[functools.partial(e1, n=i, v1=2, v2=1) for i in range(10)] # this was your first example
#your second example
[functools.partial(e1, n=n, v1=2, v2=n) for n in range(10)]