Python polynomial with deegre and coefficients from user
I write a program in Python and I need to create a polynomial with deegre(n) and coefficients (a,b,c) from user. I create it but I don't know how use it like function with argument for example polynomial(x)=some value. How i can solve this?
1 answer

You can specify a polynomial using the numpy package: https://docs.scipy.org/doc/numpy/reference/routines.polynomials.html.
As an alternative you can use sympys poly function: http://docs.sympy.org/latest/modules/polys/reference.html to get a polynomial in symbolic form. To evaluate for a given x see http://docs.sympy.org/latest/modules/evalf.html
Numpy roots will find all the roots of a polynomial, given the coefficients: https://docs.scipy.org/doc/numpy1.13.0/reference/generated/numpy.roots.html
(It might be useful to know (if you don't happen to have them from input) that you can obtain the coefficients from the sympy poly using all_coeffs function: http://docs.sympy.org/0.7.1/modules/polys/reference.html#sympy.polys.polytools.Poly.all_coeffs)
If you want to implement from first principals then I suggest looking at the reference in https://docs.scipy.org/doc/numpy1.13.0/reference/generated/numpy.roots.html.
NB: A degree zero polynomial (although I'm not sure if you meant that) is a constant and has no root unless equal to zero.
Some hints when writing your program:
 Prompt and obtain user input for poly order and then for each coefficient. Store the coefficients in a list. Also prompt and obtain user input for the x value to evaluate the polynomial for.
 If using sympy construct your polynomial object using the list.
 If using sympy evaluate your polynomial for the x value using evalf. If numpy then call a function that takes the list and the x value and evaluates the polynomial using the numpy library.
 Then call numpy.roots with your list of coefficients.
See also questions close to this topic

Getting nan in tensorflow
I wanted to build a simple machine learning model with tensorflow so that I could understand the process of machine learning and be able do stuff myself.
The dataset that I decided to use are from kaggle.
https://www.kaggle.com/andonians/randomlinearregression/version/2
Since I'm a beginner I didn't want to divide the dataset into 2 parts, namely training and validation.
My code is as follows
train=train.reindex(np.random.permutation(train.index)) train['x']=train['x']/(train['x'].max()) train['y']=train['y']/(train['y'].max()) train_features=np.array(train[['x']]) train_label=np.array(train[['y']]) train_features=tf.convert_to_tensor(train_features) train_label=tf.convert_to_tensor(train_label) w=tf.convert_to_tensor(tf.Variable(tf.truncated_normal([1,700],mean=0.0,stddev=1.0,dtype=tf.float64))) b=tf.convert_to_tensor(tf.Variable(tf.zeros(1,dtype=tf.float64))) def cal(x,y): prediction=tf.add(tf.matmul(w,x),b) error=tf.reduce_mean(tf.square(yprediction)) return [prediction,error] y,cost=cal(train_features,train_label) learning_rate=0.05 epochs=3000 init=tf.global_variables_initializer() optimize=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) with tf.Session() as sess: sess.run(init) for i in list(range(epochs)): sess.run(optimize) print(sess.run(cost))
But the output that I get is nan. nan all the way upto 3000 lines( epochs is 3000).
I can't seem to figure out the reason. I even tried to run it without normalization i.e. without converting the values between 0 and 1. I have also decreased the learning rate to 0.0005. But it seems to have no effect.
Thanks in advance.
P.S. I have not included the test set as I first want to train and see if it works. I will add it later.

How does self.next = None store the address of next value in the linked list?
I am new to classes in Python. I am trying to implement linked lists. Can someone please explain to me how self.head.next.value outputs the next value in the list? Even though next is assigned to none but somehow it is able to print the right answer. I saw a similar post here How does self.next = None get the next value of l1? but the answer was not properly explained since I am not assigning anything to self.next.
class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element l = LinkedList(Element(1)) l.append(Element(2)) print (l.head.next.value)
The output shows : 2

Getting "SettingWithCopyWarning" while performing one hot encoding with pandas
I encountered the
SettingWithCopyWarning
in Python. I searched online but it seems that all the solutions do not work for me.The input data is like this:
id genre 0 1 Drama, Romance 1 2 Action, Drama 2 3 Action, Comedy 3 4 Thriller
The expected outcome should be:
id Drama Romance Action Comedy Thriller 0 1 1 1 0 0 0 1 2 1 0 1 0 0 2 3 0 0 1 1 0 3 4 0 0 0 0 1
I want to get the subset of the input data, add some columns and modify the added column, and return the subset. Basically, I DO NOT want to modify the original
data
, I just want to get a subset, which should be a brand new dataframe :# the function to deal with the genre def genre(data): subset = data[['id', 'genre']] for i, row in subset.iterrows(): if isinstance(row['genre'], float): continue genreList = row['genre'].split(', ') for genre in genreList: if genre in list(subset): subset.loc[i][genre] = 1 else: subset.loc[:][genre] = 0 subset.loc[i][genre] = 1 return subset
I tried many ways, but neither of them gets rid of the
SettingWithCopyWarning
:subset = data[['A', 'B']].copy()
.subset = data.filter(['A','B'], axis=1)
subset = pd.Dataframe(data[['A', 'B']])
subset = data.copy()
subset.drop(columns =['C','D'])
subset = pd.DataFrame({'id': list(data.id), 'genre': list(data.genre)})
Does anyone have any idea how to fix this? Or is there a way to surpress the warning?
Thanks in advance!!
 Lower Bound Time Complexity of Log Equations

Explanation with equations : Polyfit and Polyvalue
Actually i am trying to learn some numpy library libraries but i cannot able to understand how these libraries are working from inside. Can somebody explain me polyfit and polyval with equations by putting the value without library i already checked the numpy documentation
I checked on S0 and other places also but everybody explaing this with libraries can somebody expain me these in simple maths?
Thanks in advance

Synthetic Division on Polynomials
I need to let the user input the coefficients and the divisor, and the degree needs to be 4.
def extended_synthetic_division(dividend, divisor): '''Fast polynomial division by using Extended Synthetic Division. Also works with nonmonic polynomials.''' # dividend and divisor are both polynomials, which are here simply lists of coefficients. Eg: x^2 + 3x + 5 will be represented as [1, 3, 5] out = list(dividend) # Copy the dividend normalizer = divisor[0] for i in xrange(len(dividend)(len(divisor)1)): out[i] /= normalizer # for general polynomial division (when polynomials are nonmonic), # we need to normalize by dividing the coefficient with the divisor's first coefficient coef = out[i] if coef != 0: # useless to multiply if coef is 0 for j in xrange(1, len(divisor)): # in synthetic division, we always skip the first coefficient of the divisor, # because it's only used to normalize the dividend coefficients out[i + j] += divisor[j] * coef # The resulting out contains both the quotient and the remainder, the remainder being the size of the divisor (the remainder # has necessarily the same degree as the divisor since it's what we couldn't divide from the dividend), so we compute the index # where this separation is, and return the quotient and remainder. separator = (len(divisor)1) return out[:separator], out[separator:] # return quotient, remainder. if __name__ == '__main__': print ("POLYNOMIAL SYNTHETIC DIVISION") N = [2, 3, 4, 5] D = [1, 2] print (" %s / %s =") % (N,D), print (" %s remainder %s") % extended_synthetic_division(N, D)

Numerical Array Manipulation in swift
I have an array of numbers.
let arr = [1,2,3,4,6,7,9,10,11,12,13]
I want to calculate difference means each element with next element has difference is <1 only then remove from the list (exa. 1 and 2 then 2  1 = 1 remove element and this should check upto >= 4 positions if there is continuous difference upto >= 4 the element is <1 then only it should remove.)and make array as following.
let filteredarr = [1,6,7,9]
Thanks

Should matrix entries inferior to machine precision be chopped to zero?
I have a code in doubleprecision complex arithmetic that forms large, sparse matrices (thanks to PETSc) in order to solve hydrodynamic stability problems where high accuracy is typically needed (results converged to 7/8 digits, say)
The resulting linear system Ax=b is solved by means of parallel LU decomposition. I'm aiming at solving large 3D problems so the leading dimension of the matrix can reach several dozens of millions.
The matrix contains elements resulting from the weights of the finitedifference method multiplied by the coefficients of the different physical equations solved (flow, Reynolds number...) and metric terms.
If one matrix entry is lower in absolute value than the doubleprecision machine accuracy, I discard it and chop it to zero. Would you consider that a sane approach, or, at the very least, pointless? One reason is that we want to save every possible MegaByte of memory. But what's open to debate is whether
'Very small' entries might contaminate the LU inversion process and make it unstable while increasing fillin.
If matrix entries close to machine precision are used in the process, I would assume that the result of any arithmetic operation involving those entries can be considered "unreliable"? If yes I don't see why they should be kept.
I'm aware that machine precision is a different concept than smallest representable positive number. Therefore it's possible my reasoning is conceptually wrong and would enjoy having your opinion or corrections. Thanks!

Calculating acceleration by numerical differentiation in Python
From stylus movement measurements I got two measurements: the time and the distance. So I have two arrays, first an array of timestamps (in milliseconds) and then an array of the same size of distance measurements. For example the two arrays could look like:
distance = [1.4142,1.0000,1,0,1.0000,1.0000,0,0,1.0000,1.0000,0,1.0000,2.0000,2.2361,0,3.0000,3.6056,3.1623,3.1623,0,3.6056,3.1623,3.1623,0,1.4142,2.2361,1.0000,0,0] timestamps = [1563203.5,1563208,1563210.5,1563213.5,1563218.5,1563223.5,1563226.5,1563229,1563233.5,1563238.5,1563242.5,1563245,1563248.5,1563253.5,1563258,1563260.5,1563263.5,1563268.5,1563273.5,1563276.5,1563279,1563283.5,1563288.5,1563292.5,1563295,1563298.5,1563303.5,1563307,1563317.5]
I think the first derivative gives me the speed and the second derivative gives me the acceleration.
I'm interested in calculating the acceleration using numerical differentiation. How can this be done in python?

Changing coefficients modulo p in a SymPy polynomial
I took a cryptography course this semester in graduate school, and once of the topics we covered was NTRU. I am trying to code this in pure Python, purely as a hobby. When I attempt to find a polynomial's inverse modulo p (in this example p = 3), SymPy always returns negative coefficients, when I want strictly positive coefficients. Here is the code I have. I'll explain what I mean.
import sympy as sym from sympy import GF def make_poly(N,coeffs): """Create a polynomial in x.""" x = sym.Symbol('x') coeffs = list(reversed(coeffs)) y = 0 for i in range(N): y += (x**i)*coeffs[i] y = sym.poly(y) return y N = 7 p = 3 q = 41 f = [1,0,1,1,1,0,1] f_poly = make_poly(N,f) x = sym.Symbol('x') Fp = sym.polys.polytools.invert(f_poly,x**N1,domain=GF(p)) Fq = sym.polys.polytools.invert(f_poly,x**N1,domain=GF(q)) print('\nf =',f_poly) print('\nFp =',Fp) print('\nFq =',Fq)
In this code,
f_poly
is a polynomial with degree at most 6 (its degree is at mostN1
), whose coefficients come from the listf
(the first entry inf
is the coefficient on the highest power ofx
, continuing in descending order).Now, I want to find the inverse polynomial of
f_poly
in the convolution polynomial ringRp = (Z/pZ)[x]/(x^N  1)(Z/pZ)[x]
(similarly forq
). The output of the print statements at the bottom are:f = Poly(x**6  x**4 + x**3 + x**2  1, x, domain='ZZ') Fp = Poly(x**6  x**5 + x**3 + x**2 + x + 1, x, modulus=3) Fq = Poly(8*x**6  15*x**5  10*x**4  20*x**3  x**2 + 2*x  4, x, modulus=41)
These polynomials are correct in modulus, but I would like to have positive coefficients everywhere, as later on in the algorithm there is some centerlifting involved, so I need to have positive coefficients. The results should be
Fp = x^6 + 2x^5 + x^3 + x^2 + x + 1 Fq = 8x^6 + 26x^5 + 31x^4 + 21x^3 + 40x^2 + 2x + 37
The answers I'm getting are correct in modulus, but I think that SymPy's
invert
is changing some of the coefficients to negative variants, instead of staying inside the mod.Is there any way I can update the coefficients of this polynomial to have only positive coefficients in modulus, or is this just an artifact of SymPy's function? I want to keep the SymPy
Poly
format so I can use some of its embedded functions later on down the line. Any insight would be much appreciated! 
If X ≤p Y can Y ≤p X?
I think the answer is no, but I'm having trouble with how I understand the problem. In layman, it's essentially asking that if problem x can be reduced to problem y in polynomial time then y can also be reduced to x in polynomial time, right? And from how it's written using inequalities, it should be false.
If X ≤p Y in layman this suggests that X can be reduced in polynomial time to Y
The question is then can Y ≤p X which in layman suggests that y be reduced in polynomial time to X
This problem is just confusing me a little.

Multiply Polynomials Infinite loop
Whenever the multiply method gets called the next pointer never gets updated and point on itself, even though the programs work and update properly everything when.
#include <iostream> using namespace std; class Term{ public: Term(int c, int p); Term(const Term &t2); Term* next; int coefficient, power; friend class Polynomial; }; Term::Term(const Term &t2){ this>coefficient = t2.coefficient; this>power = t2.power; this>next = t2.next; } Term::Term(int c, int p){ coefficient = c; power = p; next = NULL; } class Polynomial{ public: Polynomial(Term t); void add(Polynomial p); void print(); Term* poly; Polynomial multiply(Polynomial p); }; Polynomial::Polynomial(Term t){ poly = &t; } Polynomial Polynomial::multiply(Polynomial p){ Polynomial temp (Term(0,0)); Term* temp1 = poly; Term* temp2 = p.poly; while (temp1 != NULL){ while(temp2 != NULL){ int p = temp1>power + temp2>power; int c = temp1>coefficient * temp2>coefficient; temp.add(Polynomial(Term(c, p))); temp2=temp2>next; } temp1 = temp1>next; } cout << temp.poly; // temp.print(); return temp; } void Polynomial::add(Polynomial p){ p.poly>next = poly; poly = p.poly; } void Polynomial::print(){ Term* temp = poly; while(temp != NULL){ if (temp>coefficient!=0){ cout << temp>coefficient << "*x^" << temp>power; if(temp>next != NULL) cout << " + "; } temp = temp>next; } } int main(){ Polynomial p (Term(10,0)); p.add(Polynomial (Term(1,1))); p.add(Polynomial (Term(9,7))); p.add(Polynomial (Term(5,10))); Polynomial pp = p.multiply(p); p.print(); system("pause"); pp.print(); return 0; }
The print method works only before multiplying, after multiplying it keeps printing the first element infinitely. The multiplication method should be void but I'm trying to get it working, so I'm trying to have it return a new Polynomial object.