Mathematica Asked by BP75 on August 13, 2021
I’d like to understand how the Refine
function works internally.
I tried to create my own Refine
function to support basic cases, my goal is not to reproduce the whole Refine
function but to understand how it is built in the kernel.
For example:
In[0]:= Refine[Sqrt[x^2], x > 0]
Out[0]:= x
A naive attempt is to create the rule:
MyRefine[Sqrt[x_ ^ 2], x_ > 0] := x
Obvioulsy, it works with the following:
In[1]:= MyRefine[Sqrt[a ^ 2], a > 0]
Out[1]:= a
But not with:
In[2]:= MyRefine[Sqrt[a ^ 2], a > 1]
Out[2]:= MyRefine[Sqrt[a^2], a > 1]
How to write a rule which works for any positive value in assumptions (a > 1
also means a > 0
)?
For example, I’d like that MyRefine
function behave as follows:
In[3]:= $Assumptions:= z > 1
In[4]:= MyRefine[Sqrt[a ^ 2], a > z]
Out[4]:=a
My current output is of course Out[4]:= MyRefine[Sqrt[a ^ 2], a > z]
Actually, my question is more general. Another example:
In[5]:= Refine[Sqrt[x^2], Element[x, Reals]]
Out[5]:= Abs[x]
Naive attempt:
MyRefine[Sqrt[x_ ^ 2], Element[x_, Reals]]:= Abs[x]
Obvioulsy working with:
In[6]:= MyRefine[Sqrt[a^2], Element[a, Reals]]
Out[6]:= Abs[a]
But not with the following (whereas Integers is a subset of Reals):
In[7]:= MyRefine[Sqrt[a^2], Element[a, Integers]]
Out[7]:= MyRefine[Sqrt[a^2], Element[a, Integers]]
I have no idea about the approach to achieve this. Which kind of rules must I write? Is there a known algorithm behind?
Any help would be greatly appreciated.
Trying to implement your MyRefine
through pattern matching alone is unlikely to work, as it would require explicitly considering a huge number of corner cases. Indeed, I very much doubt that Refine
is based on this approach. It must have much more advanced internal "intelligence" similar to Simplify
. I have no idea how that is implemented, but I am certain that it is far from trivial.
For instance:
ClearAll[MyRefine]
MyRefine[expr_, assumptions_] := Simplify[expr, assumptions]
MyRefine[Sqrt[a^2], 2 a - 1 > 1] (* Out: a *)
Assuming[z > 1, MyRefine[Sqrt[a^2], a > z]] (* Out: a *)
Answered by MarcoB on August 13, 2021
I'm not sure that your approach will give you much insight into how Refine
works internally. Perhaps a better starting point is the internal implementation notes which state:
When assumptions specify that variables are real, polynomial constraints are handled by cylindrical algebraic decomposition, while linear constraints are handled by the simplex algorithm or Loos–Weispfenning linear quantifier elimination. For strict polynomial inequalities, Strzebonski's generic CAD algorithm is used.
Answered by Simon Woods on August 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP