Calculation where output is square polynomial plus remainder - sympy

My son is learning how to calculate the formula for a parabola using a directrix and focus point on his Khan Academy course. (a,b) is the focus point, k is the parameter for the directrix as y=k. I wanted to show him a simple way to check his results using Sympy; programming helps hugely in solidifying internal algorithms. Step 1 is clearly to set the equation out.
Parabola = Eq(sqrt((y-k)**2),sqrt((x-a)**2+(y-b)**2))
I first solved this for y, intending then to show how to substitute values and derive the equation, thus:
Y = solve(Parabola,y)
This was in a reasonable form, having collected the 1/(2b-2k) to the outside.
Next, I substituted the value of the focus and directrix into the equation, obtaining the equation y= 1/6*(x**2+16*x+49), which is correct.
He needed next to resolve this in a form (x+c1)(x+c2)+remainder. There does not seem to be a direct way to factor from the equation above into this form, at least not from an hour searching the docs.
Answer = Y[0].subs({a:-8,b:-1,k:-4})
factor(Answer,deep=True)
Of course I understand how to reduce to a square factorization plus remainder; my question is solely whether this is possible in sympy and, if so, how?
A second, perhaps trivial, question is why Sympy returns some factorizations as (constant - x) where (x -constant) is preferred: is there a way of specifying the form?
Thanks for any help, on behalf of my son, to whom I am showing the wonders of Sympy.

The process is usually called "completing the square". It is not implemented as a single SymPy method, but one can use the SymPy equation solver to find the coefficients of such a form of the polynomial:
>>> var('A B C')
>>> solve(Eq(Answer, A*(x-B)**2 + C), [A, B, C])
[(1/6, -8, -5/2)]
So the parabola vertex is at (8, -5/2), and the polynomial can be written as 1/6*(x+8)**2 - 5/2

Related

Find one solution of equation via sympy solve()

Is there a way to find one solution of a complicated equation via sympy. It seems finding all the solutions is too sophisticated.
I have tried to put quik = True but it does not improve the resolution.
If the equation is a polynomial you can request a particular RootOf solution; if it is a univariate expression you can get a numerical solution "near some intial guess" with nsolve.

How to create and calculate a formula using an unknown number of variables in C++

Okay, so this is going to be very complicated to explain through text but I will do my best to try.
I am making a universal calculator where one of the function of the calculator is to process a formula when given an unknown number of variables. I have seen some ways to do this but for how i'm trying to use this calculator, it wont work.
Example for sum of function:
while (cin >> input)
count++;
Normally this would work but the problem is that I can't have the user input the values over and over again for one formula like for this formula: Formula Example
(Sorry its easier for me to explain through a picture) In it there are multiple times where I have to use the same numbers over and over again. Here is the entire process if you need it to understand what I'm saying:
Entire problem
The problem is that normally I would add another float for every point graph but I don't know ahead of time number of floats the user is going to enter in. The ideal way to do this is for the program to ask the user for all the points on the table and for the user to input those points in a format like: "(1,2) (2,4) (3,6)..."
Thinking ahead, would I make a function where the program creates an integer and assigns the integer to a value on the fly? But then how would the actual math formula interact with the new integers if they haven't been created yet?
Talking about this makes my head hurt....
I actually want to say more:
One idea that I tried to make in my head was something like
string VariableName = A [or something]
Then you would reassign VariableName = "A" to VariableName = "B" by something like VariableName = "A"+ 1 (which would equal B).
Then you would repeat that step until the user inputs a invalid input. But obviously you can't do math with letters so I wouldn't know how to do it.
I think that you are overthinking this. It's pretty simple and it doesn't need to store the input values.
The main thing to note is that you need to compute (step 2) the sum of the values of X and Y, the sum of their product and the sum of X squared. To compute the sum of a lot of values you don't need all the values together, but just one at the time. Exactly as when a user provides them. So declare four variables: sx, sy, sxy, sxx. Initialize them to 0. At every couple of X and Y you get, add it to sx and sy, add their product to sxy and the product of X with itself to sxx.
Now you've got all you need to compute the final result for a and b.
Anyway a good C++ book would be useful.

How can you remove only the interaction terms in a polynomial regression using scikit-learn?

I am running a polynomial regression using scikit-learn. I have a large number of variables (23 to be precise) which I am trying to regress using polynomial regression with degree 2.
interaction_only = True, keeps only the interaction terms such as X1*Y1, X2*Y2, and so on.
I want only the other terms i.e, X1, X12, Y1, Y12, and so on.
Is there a function to get this?
There is no such function, because the transormation can be easily expressed with numpy itself.
X = ...
new_X = np.hstack((X, X**2))
and analogously if you want to add everything up to degree k
new_X = np.hstack((X**(i+1) for i in range(k)))
I know this thread is super old. But for folks like me who just getting started can use petsy. Checkout the answer discussed here ->
how to the remove interaction-only columns from sklearn.preprocessing.PolynomialFeatures

Better alternative to divide and conquer algorithm

First let me explain the problem I'm trying to solve. I'm integrating my code with 3rd party library which does quite complicated financial predictions. For the purposes of this question let's just say I have a blackbox which returns y when I pass in x.
Now, what I need to do is find input (x) for a given output (y). Since I know lowest and highest possible input values I wrote the following algorithm:
define starting input range (minimum input value to maximum input value)
divide the range into two equal parts and find output for a middle value
find which half output falls into
repeat steps 2 and 3 until range is too small to divide any further
This algorithm does the job nicely, I don't see any problems with it. However, is there a faster way to solve this problem?
It sounds like x and y are strongly correlated (i.e. as x increases, so does y), as otherwise your divide and conquer algorithm wouldn't work.
Assumuing this is the case, and you could work out a correlation factor, then you might be able to multiply the midpoint by the correlation factor to potentially hone in the expected value quicker.
Please note that I've not tested this idea at all, but it's something to think about. Possible improvements would be to make the correlationFactor a moving average, or precompute it based on, say, the deciles between xLow and xHigh.
Also, this assumes that calling f(x) is relatively inexpensive. If it is expensive, then the increased number of calls to f(x) would dwarf any savings. In fact - I'm starting to think this is a stupid idea...
Hopefully the following pseudo-code illustrates what I mean:
DivideAndConquer(xLow, xHigh, correlationFactor, expectedValue)
xMid = (xHigh - xLow) * correlationFactor
// Add some range checks to make sure that xMid is within xLow and xHigh!!
y = f(xMid)
if (y == expectedValue)
return expectedValue
elseif (y < expectedValue)
correlationFactor = (xMid - xLow) / (f(xMid) - f(xLow))
return DivideAndConquer(xLow, xMid, correlationFactor, expectedValue)
else
correlationFactor = (xHigh - xMid) / (f(xHigh) - f(xMid))
return DivideAndConquer(xMid, xHigh, correlationFactor, expectedValue)

simplifying expressions with hyperbolic functions

Is there a command in sympy to simplify sinh(x)+cosh(x) to exp(x)? If I issue
from sympy import *
x = Symbol('x')
(sinh(x)+cosh(x)).simplify()
I just get sinh(x)+cosh(x) back, but I want to see exp(x) instead.
Even assuming that the simplify function in sympy was very good, what you suggest may not have worked, because what is "simple" is not rigorously defined.
I think what you want is the functionality present in .rewrite:
In [1]: (sinh(x)+cosh(x)).rewrite(exp)
Out[1]:
x
e
You can use .rewrite for many other transformations including gamma <-> combinatorics and inverse trig <-> logarithms.