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

Connecting to API issues
I am new to Python and am trying to use it to connect to Americommerce API. They have an example on git. It doesn't seem to work though. I add the url to STORE_DOMAIN, key to ACCESS_TOKEN, and app id to STORE_ID.
The only one that seems to matter is the web url. If I mispell it I get coonection errors, however the key and id I can enter whatever I want there and get the same results. here is the script
#!/usr/bin/env python3 # The 'requests' module is available via pip: "pip install requests" # You can find more documentation about requests at http://docs.pythonrequests.org/en/latest/ import requests import json import locale import sys STORE_DOMAIN = "http://www.example.com" ACCESS_TOKEN = "key" STORE_ID = "app_id" # This should reflect your store's ID locale.setlocale(locale.LC_ALL, '') # Searches for and returns the customer that matches the info passed in, # if no customer is found a new one is created and returned def get_customer(firstName, lastName, email): # setup headers headers = { 'XACAuthToken': ACCESS_TOKEN, 'ContentType': 'application/json' } # build API call to check if customer already exists (using email) uri = '{}/api/v1/customers?email={}'.format(STORE_DOMAIN, email) # include verify=False if using dev certificate # r = requests.get(uri, headers = headers, verify=False) r = requests.get(uri, headers = headers) # see if a customer was found customer = r.json() if (customer['total_count'] > 0): return customer['customers'][0] # no customer found, so lets create a new one data = { 'last_name': doe, 'first_name': john, 'email': johndoe@email.com, 'store_id': 4 } # build API call to post a new customer uri = '{}/api/v1/customers'.format(STORE_DOMAIN) # include verify=False if using dev certificate # r = requests.post(uri, headers=headers, data = json.dumps(data), verify=False) r = requests.post(uri, headers=headers, data = json.dumps(data)) # return newly created customer return r.json() if __name__ == '__main__': customer = get_customer('John', 'Doe', 'JohnDoe@email.com') first_name = customer['first_name'].encode('utf8') last_name = ',{}\n'.format(customer['last_name']).encode('utf8') email = customer['email'].encode('utf8') sys.stdout.buffer.write(first_name + last_name + email)
I get this result when I run this:
Traceback (most recent call last): File "./getStuff.py", line 57, in <module> customer = get_customer('John', 'Doe', 'JohnDoe@email.com') File "./getStuff.py", line 35, in get_customer if (customer['total_count'] > 0): KeyError: 'total_count'
Please, a little help here would be appreciated. Ive been stuck on this for a bit now.

Where to put tab completion configuration in python?
python tab completion Mac OSX 10.7 (Lion)
The above link shows that the following code can be used for autocompletion in python.
import readline import rlcompleter if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete")
But I don't see where to put it so that it can be loaded at startup. I tried
~/.pythonrc
, but it did not work.Does anybody know what is the current way to load such a configuration automatically for an interactive python session?

Changing a predictor input to Linear Discriminant Analysis (LDA) and comparing the output
I've been running Linear Disriminant Analysis (LDA) through python (using the method from Sebastian Raschka).
My data is related to galaxies  I've been trying to classify galaxies as either nonmerging or merging based upon a set of predictors (9 total). I've been varying the measurement of one of the predictors and rerunning LDA.
Is this a statistically legitimate thing to do? I was also wondering how to compare the runs of LDA and answer the question: are they different if I change the way I measure this one predictor?
My first discriminant component (PCA1 or LDA1 in this case) has a much larger eigenvalue than all others for all runs, so one thing I've been trying is comparing eigenvector 1 between the different runs of LDA. The ordering of the predictors changes as does their relative values. I guess I should mention that I've also normalized all the predictors prior to LDA.
So is it legitimate to directly compare the eigenvector 1 values for each predictor and if they change in value or order this indicates that the different measurement of the predictor is significant? How much of a change would be necessary to call this 'significant'?
Here is an example of eigenvectors of two runs where I change the 2nd to last input predictor:
Eigenvector 1 for Model1: [[0.092 ] [0.0066] [ 0.4605] [ 0.7649] [0.3991] [ 0.1067] [ 0.0826] [0.126 ] [ 0.0314]] Eigenvalue 1: 2.29e+00 Eigenvector 1 for Model2: [[ 0.0824] [0.0012] [0.3643] [0.7967] [ 0.4032] [0.0449] [0.0769] [0.0297] [ 0.2331]] Eigenvalue 1: 2.70e+00
Thank you for your input!

Get normal form of a plynomial from roots
I'm sure there already is a solution to my problem, but I cannot find it on the net, that's why I'm asking this question.
So far I got all the zeros of a polynomial computed with C#
var poles = new Complex[order];
I could now write my polynomial as a product like this
H(z) = prod_k(z  z_k)
where
prod_k
is the product fromk=0
tok=order
andz_k
is thekth
root.How do I get a polynomial in normal form from that.
H(z) = a_n * z^n + a_n1 * z^n1 + ... + a_0
There must be some kind of library, but i cant find any.

Has SymPy lost the functionality to divide by multiple polynomials?
New to SymPy, and am experimenting with dividing polynomials. Currently, I am running Python 3.6.4 with SymPy 1.1.1 (pip installed). After browsing their documentation, I found on their 0.6.7 documentation page the following useful example:
Another option is division by multiple polynomials at the same time. In general, the output is not unique and depends on the order of the divisors and the given monomial order (if specified).
>>> f = x*y + y*z + z*x >>> g1 = x + 1 >>> g2 = 2*y + 1 >>> q, r = div(f, [g1, g2], x, y, z) >>> q z [y + z, 1/2 + ] 2 >>> r 3*z 1/2   2
However, this feature, at least in the 1.1.1 documentation page is nonexistent. And, more so, if I try to attempt a similar operation on 1.1.1, I get the following error:
>>> f = x*y + y*z + z*x >>> g1 = x + 1 >>> g2 = 2*y + 1 >>> q, r = div(f, [g1, g2], x, y, z) Traceback (most recent call last): File "C:\[...]\Python\Python36\lib\sitepackages\sympy\polys\polytools.py", line 4659, in div (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) File "C:\[...]\Python\Python36\lib\sitepackages\sympy\polys\polytools.py", line 4266, in parallel_poly_from_expr return _parallel_poly_from_expr(exprs, opt) File "C:\[...]\Python\Python36\lib\sitepackages\sympy\polys\polytools.py", line 4312, in _parallel_poly_from_expr raise PolificationFailed(opt, origs, exprs, True) sympy.polys.polyerrors.PolificationFailed: can't construct polynomials from x*y + x*z + y*z, [x + 1, 2*y + 1] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\[...]\Python\Python36\lib\sitepackages\sympy\polys\polytools.py", line 4661, in div raise ComputationFailed('div', 2, exc) sympy.polys.polyerrors.ComputationFailed: div(x*y + x*z + y*z, [x + 1, 2*y + 1]) failed without generators
I highly doubt this feature has been removed, as this is quite an important feature, especially for affine variate and Groebner basis analysis, (the topic I am studying)
Can someone point me toward a working example of this with SymPy?

Is there an easy way to calculate irreducible polynomials in GF(2^n)?
Is there an easy way to calculate irreducible polynomials in GF(2^n) or is it more practical to just memorize them? I hate memorizing this stuff just as much as the next person but I can't figure out a fast way to get them that doesn't involve multiple divisions that take way too long.

Most Simple Way to Read in Numerical Input With Rust
This question was asked back in May of 2015, nearly 3 years ago here, which was when the first stable release came out. With Rust being a newer programming language, I figured it was suitable to ask the question again, since development in the community has rapidly occurred.
The original solution (proposed by @Hauleth) from the first time this was asked is:
use std::io; fn main() { let mut input_text = String::new(); io::stdin() .read_line(&mut input_text) .expect("failed to read from stdin"); let trimmed = input_text.trim(); match trimmed.parse::<u32>() { Ok(i) => println!("your integer input: {}", i), Err(..) => println!("this was not an integer: {}", trimmed) }; }
... which seems to be closely related to what is discussed in the Rust book version 2 provided here. However, this seems fairly convoluted when compared to other input methods for other languages, such as C++.
Another solution was to use text_io, which is a very handy, but has its quirks. For example, I am not able to use
println!()
to print items before executingread!()
, which seems to be a fairly significant drawback.So, my question is, has a more simple method for numerical input been developed for Rust since the question was first asked 3 years ago?

Why would someone use empirical sum instead of numerical integration methods?
In the context of a scientific computing application, using data coming from (powerful) embedded systems, acquiring raw data (but from calibrated acquisition electronics), I have been asked to integrate these data (in RT), with an empirical sum, instead of making use of usual numerical methods. (Important point : The values retrieved where floats).
When I was asking why not using these usual numerical methods (e.g. Simpson's, midpoint rule, trapezoidal rule, etc.), I could not get any answer. Then, I am wondering why someone would want to perform it that way (while knowing that computational power is not an issue).
The acquisition application on the embedded system is in C++03, compiled with GCC 4.4.7, the average being performed looking somewhat like this (this code is executed each time the acquisition is performed) :
float sum = 0.0; for (int i = 0; i < DATA_BLOCK_LENGTH; i++) { sum += data[i] } sum /= DATA_BLOCK_LENGTH;
This (pseudo)code performs the average from a trace of the signal received, usually looking like this most of the time.
The previous constant, DATA_BLOCK_LENGTH, is usually set to the maximum (2048, which is the size of electronics buffer).

R  Combine non numerical and numerical data together in the same cell in a dataframe
I want to combine cell values with numeric and character data into the same cell.
Specifically, I'm trying to combine named columns with the 'SEM' columns, with a ± symbol in between, to eventually become a table I can publish with latex
# A tibble: 4 x 10 Variety n Probes Probes SEM Walks Walks SEM Cleans Cleans SEM Off_Leaf Off_SEM <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 10LB mean 41 1.40 0.140 0.710 0.170 0.460 0.140 0.120 0.0520 2 3LB mean 48 1.50 0.130 0.880 0.170 0.310 0.0900 0.190 0.0710 3 4LB mean 43 1.80 0.160 1.10 0.190 0.370 0.120 0.280 0.190 4 RB mean 44 2.80 0.390 1.50 0.260 0.180 0.0750 0.0910 0.0440
Is there any way to make the previous table look like this:
# A tibble: 4 x 6 Variety n Probes Walks Cleans Off Leaf <chr> <int> <chr> <chr> <chr> <chr> 1 10LB 41 1.4 ± 0.1 0.7 ± 0.2 0.5 ± 0.1 0.1 ± 0.05 2 3LB 48 1.5 ± 0.1 0. 9± 0.2 0.3 ± 0.09 0.2 ± 0.07 3 4LB 43 1.8 ± 0.2 1.1 ± 0.2 0.4 ± 0.1 0.3 ± 0.2 4 RB 44 2.8 ± 0.4 1.5 ± 0.3 0.2 ± 0.07 0.09 ± 0.04
while remaining in R?

Add two polynomials
I have a great request for you, could someone give me a solution to the problem of "write a program for adding two polynomials with tree variables based on structure and linked list Not using class"
Poly1: 5x^2 + 2z  6 Poly2: 6xy^2  6y + 3yz + 8
Thanks

curve fitting to unusual data
I have a data with 722 data points like this:
earthquake distances from main event (km):159.678811, 43.985747, 17.909659, 1.163744, 13.375051, 2.706271, 11.464427, 6.903845, 157.994631 earthquake magnitudes: 4.70, 3.00, 4.77, 4.15, 4.98, 4.25, 2.50, 4.02, 4.47
I plotted the log of distances in xaxis and magnitudes in yaxis and found a picture like this:
How do I fit this graph. Would it be useful to take the help of splines?

Adding Polynomials in Linked List
I have an assignment that wants me to add polynomials into linked lists and then add them together. I am provided a generic linked list class and a class called polyUnit that is the type stored in the linked list. I can not edit either of these only implement them and use their methods. I am also given a main method which I can not edit either.
I am not sure how to implement the polyUnit class in with the linked list. I know I need a initialization() method to handle that call as well as an add() method. But beyond that any help in the right direction would be great.
When the inputs for a and b are 3.2x^2  4x + 5 and 2x^7 + 4x^2  5, c will be 2.0x^7+ 7.2x^2  4.0x^1.
public class PolyB extends SingleLinkedList<polyUnit> { … public static void main(String args[]) { PolyB a = new PolyB (); PolyB b = new PolyB (); PolyB c = new PolyB (); a.initialization(); b.initialization(); c = a.add(b); System.out.println(a); System.out.println(b); System.out.println(c); } }
here is the poly unit class:
public class polyUnit { private double c; private int e; public polyUnit(){ c=0; e=0; } public polyUnit(double c, int e){ this.c = c; this.e = e; } public double get_c(){return c;} public int get_e(){return e;} public void set_c(double c){this.c = c;} public void set_e(int e){this.e = e;} }