How can i sum two polynomials? in python - python

I have to make a program that can take from the user two polynomials (string) to calculate the result. The problem is that in polynomials the program must sum the coefficients that have the same power. I have to make it using class. I'm beginner in python. Thank you

Do you really want to parse the polynomials from strings? Because you can always represent polynomials as a list of coefficients for each of the terms. E.g.
[3 0 2 1]
would represent the polynomial
3 + 2*x^2 + x^3 == 0
Once you have that representation, summing the polynomials is trivial.
If you want to accept strings as input, you should first extract the coefficients from the string and build a coefficient vector, and then proceed.
Edit: Reversed the representation of the polynomial to make it more natural in the sense that element i represents the coefficient of x^i.

Related

What are the odds of a repeat in numpy.random.rand(n) (assuming perfect randomness)?

For the moment, put aside any issues relating to pseudorandom number generators and assume that numpy.random.rand perfectly samples from the discrete distribution of floating point numbers over [0, 1). What are the odds getting at least two exactly identical floating point numbers in the result of:
numpy.random.rand(n)
for any given value of n?
Mathematically, I think this is equivalent to first asking how many IEEE 754 singles or doubles there are in the interval [0, 1). Then I guess the next step would be to solve the equivalent birthday problem? I'm not really sure. Anyone have some insight?
The computation performed by numpy.random.rand for each element generates a number 0.<53 random bits>, for a total of 2^53 equally likely outputs. (Of course, the memory representation isn't a fixed-point 0.stuff; it's still floating point.) This computation is incapable of producing most binary64 floating-point numbers between 0 and 1; for example, it cannot produce 1/2^60. You can see the code in numpy/random/mtrand/randomkit.c:
double
rk_double(rk_state *state)
{
/* shifts : 67108864 = 0x4000000, 9007199254740992 = 0x20000000000000 */
long a = rk_random(state) >> 5, b = rk_random(state) >> 6;
return (a * 67108864.0 + b) / 9007199254740992.0;
}
(Note that rk_random produces 32-bit outputs, regardless of the size of long.)
Assuming a perfect source of randomness, the probability of repeats in numpy.random.rand(n) is 1-(1-0/k)(1-1/k)(1-2/k)...(1-(n-1)/k), where k=2^53. It's probably best to use an approximation instead of calculating this directly for large values of n. (The approximation may even be more accurate, depending on how the approximation error compares to the rounding error accumulated in a direct computation.)
I think you are correct, this is like the birthday problem.
But you need to decide on the number of possible options. You do this by deciding the precision of your floating point numbers.
For example, if you decide to have a precision of 2 numbers after the dot, then there are 100 options(including zero and excluding 1).
And if you have n numbers then the probability of not having a collision is:
or when given R possible numbers and N data points, the probability of no collision is:
And of collision is 1 - P.
This is because the probability of getting any given number is 1/R. And at any point, the probability of a data point not colliding with prior data points is (R-i)/R for i being the index of the data point. But to get the probability of no data points colliding with each other, we need to multiply all the probabilities of data points not colliding with those prior to them. Applying some algebraic operations, we get the equation above.

Why is the absolute value of a complex number a floating point number?

In python3:
>>> abs(-5) == 5
and
>>> abs(5) == 5
but
>> abs(5+0j) == 5.0
The absolute value of a complex number a+bj, is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. In other words, it's sqrt(a2 + b2).
I take it that the real question is “Why does Python's abs return integer values for integer arguments but floating point values for complex numbers with a plain integer value.”
Concerning the argument and result types of abs there are three main cases:
argument is integer ⇒ result is integer; so it's safe to say that abs(-5) returns an integer (5).
argument is real (floating point) ⇒ result is real; so abs(5.1) returns a floating point number (5.1).
argument is complex ⇒ the result is a floating point number but the decision whether it has an exact integer value depends on the values of the real/imaginary parts of the argument.
This decision in the last case is far from trivial: abs(5+0i) has an integer value, so has abs(3+4i) (Pythagoras) but abs(5+2i) has not. In other words, it would not make sense to create an "integer complex" type and provide an abs implementation for it; the result would in most cases not be integer.
So it is quite sensible not to extend the integer/real distinction into the fields of complex numbers. (It would work for addition but the practical benefit would be close to zero.)
Assuming you know about the definition of the norm of a complex number, then your question becomes: why is abs(5j) returning 5.0 instead of 5 even though you provided an int as imaginary component?
The answer is type consistency. Since abs returns a float for complex numbers, there is no reason to make a special case and return an int if the output happens to be a round number.
Also, note that the same reasoning applies for the components of your imaginary numbers which are always stored as float.
z = 1 + 1j
z.real # 1.0
z.imag # 1.0
Because the absolute value of a complex number is the distance from origin to the number on the complex plane (where the two components of the complex number form the coordinates).
The imaginary i and real r components of a complex number can be seen as coordinates on a plane, and you can calculate the distance from the origin ((0, 0)) by using Pythagorean distance formula, sqrt(i**2 + r**2).
The distance can be expressed as a floating point (real) number, there is no imaginary component.
It also can’t be an integer, because the Pythagorean distance is not always a convenient whole number (unlike the absolute value of an integer, which can only ever be another integer).

How can I find integers in a range which are sums of max. 4 perfect square numbers in Python?

I have this mathematical, Python problem, where I have to find all numbers in a range which are the sum of maximum 4 square numbers. I can't think about a working algorithm, with my basic knowledge. Can you help me out with the algorithm, or an idea of where to start? I'm not asking for the code. Thanks in advance!
According to this Lagrange theorem, you can return the whole positive range because
every natural number can be represented as the sum of four integer
squares.
It means that the algorithm can be written as:
def my_algorithm(integer_range):
return [i for i in integer_range if i >= 0]
Check this link out.
This wikipedia page will solve your problem!
Basically, all whole numbers can be represented as a sum of 4 perfect squares.

Numerical precision in python

I've been doing simple numerical experiments with python, like computing
factorials. For instance, compute the factorial of 32:
My routine:
2.6313083693369503e+35
From scipy.misc:
2.6313083693369355e+35
I want to point out that my routine calculates the logarithm of the factorial,
it calculates the sumation of logarithms starting from 1 to 32 (in this case)
and then I just take the exp function (I do it this way because of stuff learned from
Fortran 90).
It is a surprise that the correct answer is
263130836933693530167218012160000000
according to pari/gp.
I would be very happy if someone can point me out to references where I can look for
correct numerical answers in Python. The documentation it's ok but only if one want
"short" numbers.
log and exp functions operate on floating points, which have limited precision. Python's integers, on the other hand, can have arbitrary precision. So, you can compute the factorial of 32 in linear space just fine using integers.
f = 1
for i in xrange(32):
f *= i + 1
print f # prints '263130836933693530167218012160000000'
You can do it this way:
import operator
n=32
print reduce(operator.__mul__,range(1,n+1))
# 263130836933693530167218012160000000

harmonic mean in python

The Harmonic Mean function in Python (scipy.stats.hmean) requires that the input be positive numbers.
For example:
from scipy import stats
print stats.hmean([ -50.2 , 100.5 ])
results in:
ValueError: Harmonic mean only defined if all elements greater than zero
I don't mathematically see why this should be the case, except for the rare instance where you would end up dividing by zero. Instead of checking for a divide by zero, hmean() then throws an error upon inputing any positive number, whether a harmonic mean can be found or not.
Am I missing something here in the maths? Or is this really a limitation in SciPy?
How would you go about finding the harmonic mean of a set of numbers which might be positive or negative in python?
The harmonic mean is only defined for sets of positive real numbers. If you try and compute it for sets with negatives you get all kinds of strange and useless results even if you don't hit div by 0. For example, applying the formula to the set (3, -3, 4) gives a mean of 12!
You can just use the Harmonic Mean define equation:
len(a) / np.sum(1.0/a)
But, wikipedia says that harmonic mean is defined for positive real numbers:
http://en.wikipedia.org/wiki/Harmonic_mean
There is a statistics library if you are using Python >= 3.6:
https://docs.python.org/3/library/statistics.html
You may use its mean method like this. Let's say you have a list of numbers of which you want to find mean:
list = [11, 13, 12, 15, 17]
import statistics as s
s.harmonic_mean(list)
It has other methods too like stdev, variance, mode, mean, median etc which too are useful.
the mathematical definition of harmonic mean itself does not forbid applications to negative numbers (although you may not want to calculate the harmonic mean of +1 and -1), however, it is designed to calculate the mean for quantities like ratios so that it would give equal weight to each data point, while in arithmetic means or such the ratio of extreme data points would acquire much high weight and is thus undesired.
So you either could try to hardcode the definition by yourself like #HYRY suggested, or may have applied the harmonic mean in the wrong context.

Categories

Resources