sympy division of multivariate polynomials - sympy

Why doesn't sympy divide this polynomial?
>>> import sympy as sp
>>> x,y = sp.symbols("x y")
>>> print(sp.div(y+x,y))
(0, x + y)
I was expecting the answer to be (1,x) because the quotient is 1 and the remainder is x. How can I get sympy to divide polynomials?
What I want is to express some polynomial p as p=aq+r where r is the remainder and q is the quotient and a is the divisor. In the example above, notice that y+x=1*x+y and so it seems to me that we should be able to find that 1 is the quotient of p by x.
some more details
Say I am working over a real multivariate polynomial ring, and say I want to express some polynomial p as p=aq+r for some non zero polynomial a and for some r with deg(r)<deg(q). By degree (deg) I mean total degree, that is, the degree of the single variate polynomial that you get when you substitute all variables with x. For example, the total degree of xy^2 is 3. Although such a pair (q,r) may not exist, if it does exist, it is unique given (p,a). Here is a proof:
Say p=aq+r and p=aq'+r' for some r st. deg(r)<deg(a) and assume q≠q'.
By subtracting these equations and rearranging we have a(q-q')=r'-r.
Notice that because q-q'β‰ 0, we have deg(a)≀deg(a(q-q'))=deg(r-r').
Thus because deg(r)<deg(a), we may conclude that deg(a)≀deg(r').
Thus if there exists such an r, this r is unique.
I point this out so as to suggest that the computation I am asking for is well defined.
It seems to me that being able to do multivariate polynomial division is a natural feature
that sympy should support. If I am wrong here, please let me know why.

See here
Given a family (π‘₯𝑖) of symbols, or other suitable objects, including numbers, expressions derived from them by repeated addition, subtraction and multiplication are called polynomial expressions in the generators π‘₯𝑖.
You need to specify the generators. Because given the expression y+x, the machine can NOT figure out which variable is the generator. It can be f(y) = x+y or f(x) = x+y.
You need to tell it the order of generators is [x,y].
print(sp.div(y+x, y,gens=[x,y]))
# (0, x + y)
If you set the order of generators to be [y,x].
print(sp.div(y+x, y,gens=[y,x]))
# (1, x)

Related

Prolog - How to get the sum of a list's elements?

I'm very new to prolog and I am trying to write a little program that, given a list, returns the sum of the list's elements. Following all the examples I've seen led me to a solution that looks like this:
addup([],0).
addup([FirstNumber | RestOfList], Total) :-
addup(RestOfList, TotalOfRest),
Total is FirstNumber + TotalOfRest.
But when I test that solution with these values:
?- addup([1,2,3,4],0).
I just get garbage values from it like _34521.
Then I tried a second solution that looks like this:
sum([], 0).
sum([H|T], N):-
X is H+N,
sum(T, X).
This one is able to add up the numbers correctly, but it is unable to pass the final value of X, which is the true answer, into N. So for the test case:
?- sum([1,2,3,4], 0).
I get an answer of 6, the final value of N, and the second-to-last value of X, instead of 10, the final value of X. Any help and/or explanations of why neither of these solutions work would be greatly appreciated. Thanks.
Firstly, the sum of an empty list is 0 - this is the base case, which you already had.
Secondly, the sum N of an element H and a list T is the sum of the list T added to H. Prolog operates on unification, so this says that N is unified with the sum of H and T, where the sum of T is unified with X using sum(T,X).
sum([], 0).
sum([H|T], N):-
sum(T, X),
N is X + H.
This gives:
?- sum([1,2,3,4],N).
N = 10.
In your original question, ?- sum([1,2,3,4], 0). actually says "this is true if the sum of the list [1,2,3,4] is 0" - you need to pass a variable as the second argument to sum to be unified with the answer.
Further information:
_34521 is a representation of an unbound variable - this says that there is a variable, but that it has not yet been unified with a value.
Secondary consideration:
For a suitably long list, the implementation above will run out of stack space, as each frame of the recursion must be stored, so that the addition can happen from the bottom up. In order to prevent a stack error, we can use a tail-recursive accumulator like so:
sum(L, N):-
sum(L, 0, N).
sum([],N,N).
sum([H|T],A,N) :-
A1 is A + H,
sum(T,A1,N).
... which retains the signature of the original method, wrapping sum/3. As there is no choice-point in the body of the rule (given that A + H is always the same for a given A and H, and the list is either empty or not), Prolog will discard each frame as it leaves scope (as there is nothing more to be done with it) and, on completion, will return to the original caller.
Simplified stack for sum([1,2,3],N) in each instance:
non-tail-recursive:
rest-of-stack
rest-of-stack,sum([1|[2,3]],_1001)
rest-of-stack,sum([1|[2,3]],_1001),sum([2|[3]],_1002)
rest-of-stack,sum([1|[2,3]],_1001),sum([2|[3]],_1002),sum([3|[]],_1003)
rest-of-stack,sum([1|[2,3]],_1001),sum([2|[3]],_1002),sum([3|[]],_1003),sum([],0)
rest-of-stack,sum([1|[2,3]],_1001),sum([2|[3]],_1002),sum([3|[]],3)
rest-of-stack,sum([1|[2,3]],_1001),sum([2|[3]],5)
rest-of-stack,sum([1|[2,3]],6)
rest-of-stack
tail-recursive:
rest-of-stack
rest-of-stack,sum([1,2,3],_1001)
rest-of-stack,sum([1|[2,3]],0,_1001)
rest-of-stack,sum([2|[3]],1,_1001)
rest-of-stack,sum([3|[]],3,_1001)
rest-of-stack,sum([],6,6)
rest-of-stack
Note that the tail-recursive stack has a limited depth for any length of list (dependent on what is calling it), where the non-tail-recursive stack goes to a depth directly proportional to the length of the list.
Thus, a call such as N is 10^7,length(L,N),maplist(=(1),L),sum(L,N). (as raised by #false) will likely fail without tail-recursion, and likely succeed with it.

How to rewrite an expression in terms of an other expression in sympy

EDIT: I am not asking how to solve an equation in terms of a given variable (as in this supposed duplicated question), but how to represent an expression in terms of an other one, as specified in the question.
I believe it is the "duplicated" question to have a misleading title.
I am very new with SymPy. I have an expression that, once expressed in terms to an other expression, should become very nice.
The problem is that I don't know how to "force" to express the original expression in terms of the other one.
This is a basic example:
import sympy as sp
sp.init_printing(use_unicode=True)
a,b,c = sp.symbols('a b c')
A = a+b+c
B = a+c
C = A.subs(a+c,B) # Expected/wanted: C = B+b
C
A.rewrite(B)
A and B could be rather complex expressions. For reference, this is my real-case scenario:
import sympy as sp
sp.init_printing(use_unicode=True)
t, w, r = sp.symbols('t w r')
S = sp.Function('S')(t)
V = (S-w*(1+r)**t)/(((1+r)**t)-1)
V
St = -(r + 1)**t*(w - S)*sp.log(r + 1)/((r + 1)**t - 1)
St
Once I write St in terms of V, I should be able to simplify to get just
St = rS(t)+rV
But I am unable to do it in SymPy.
First note that when you do something like
a,b,c = sp.symbols('a b c')
A = a+b+c
B = a+c
variables A, B are not new Sympy symbols that Sympy can understand and operate on, rather, they are aliases for the Sympy expressions a+b+c and a+c, respectively. Therefore, A.subs(a+c,B) is essentially the same as A.subs(a+c,a+c), which is, of course, meaningless. You get the idea of why A.rewrite(B) is also of no use.
I do not think that calls like expr.subs({complicated_mutlivariable_formula: new_variable}) work in Sympy. One way to do what you want is to first solve the equation complicated_mutlivariable_formula = new_variable with respect to one of the "old" variables, and, assuming a unique solution exist, use subs() to substitute this variable.
Applying this approach for the second example:
# sympy Symbol A will be used to represent expression V
A = sp.symbols('A')
# Solve the equation V==A with respect to w, which has a unique solution as a function of A
w_A = sp.solve(sp.Eq(V,A), w)[0]
# Now substitute w
St.subs({w:w_A}).simplify()

FORTRAN 77 NEQNF IMSL Solver, 2 variables, 6 equations

I am trying to use NEQNF to solve a system of 6 non linear equations. I need to determine 2 variables to solve my system. According to description i need to define "N" which is the length of "X"(variables) AND "F"(equations).
Does this mean that i can use this solver only if X=F? Because N is defindes as an integer in the example given below in the description.
Or can i define N as a vector? How does declaration of N supposed to look like in this case?
From the link you gave:
X – The point at which the functions are evaluated. (Input) X should
not be changed by FCN.
F – The computed function values at the point X. (Output)
N β€” Length of X and F.
X and F are vectors of length N (scalar!). X is the input to FCN, and F the output. So I would guess that F is (generally) not equal to X.

How to write general integration function in OCaml

I would like to write a function in OCaml that will calculate the definite integral for the given function. The problem is that I aim for the following syntax:
let sphere r phi theta = r *. sin phi *. cos theta in
let dphi = 10 in (* number of parts *)
let dtheta = 10 in (* number of parts *)
let zero = 0.0 in
let two_pi = 2.0 *. 3.14159
in
integral zero two_pi (integral zero two_pi (sphere 3.0) dphi) dtheta
The problem is that using rule like trapezoidal rule I need to write something like:
0.5 *. (f a +. f b) *. d
Which expects that the f a and f b are not partially applicated functions.
I don't expect that the result from the last integral function call will return me a float number, I'm totally fine with some functional.
I've realized that the question is very unspecific. Let me restate it in a more general way:
I have a function float->float->float which after the application of integral function should give me float->float. It should be general, so the integral of float->float should result in float.
The problem is that I need subtract two functions of the same order: f(a) -. f(b), where both of them could be float->float->float, float->float or even float->float->float.
To decrease the order of a function I need a signature like: (float->'a->float) -> ('a->float).
Is this even possible? Specifically in OCaml?
The more I think about this problem of having one function calculating the integral that can be chained, the more it seems like an impossible task/stupid way to do it.
In fact I've implemented this but using my own data type (called function_type which can be Scalar3rdOrderFunction, Scalar2ndOrderFunction, Scalar1stOrderFunction, Scalar0thOrderFunction). But for the prize of polymorphism the compiler cannot warn me when I try apply the integral three times for function float->float->float.

Ocaml fixed point implementation

I'm trying to figure out how to implement fixed point iteration in Ocaml. That is, given a function f and an x, I want to calculate what the final value of what f(f(f(x)...)) will be.
So for example, if my function is x/2 and my x=50, my answer should be 0.
So far, I have
let rec computed_fixed_point eq f x =
if (x == f x) then
x
else
computed_fixed_point eq f (f x)
This works for the function x/2 and x=50 (giving me 0), but for functions that go off to infinity or something other than 0, it doesn't seem to work.
Can another give me some advice? Thanks!
It's a little hard to understand the rationale of this problem. Not every function is going to have a fixed point. For example fun x -> (x + 1) mod 5. Not every function with a fixed point will reach the fixed point by repeated application from a distinct starting point. (I just did some googling, and fixed points like this are called "attractive fixed points".)
Here are some comments:
You shouldn't use ==, which is the physical equality operator. You possibly want to use =, equality of values.
However, I don't see what the eq parameter is for. Perhaps the caller is allowed to specify what equality to use. If so, you should use this instead of ==.