Mathematica [Mathematica] Redefining a built-in symbol

AI Thread Summary
The discussion revolves around redefining the built-in square root function in Mathematica. The user successfully creates a custom function, mySqrt, and modifies Sqrt to return either the positive or negative square root based on the input's real and imaginary parts. However, they encounter an issue where the symbol √ still refers to the original Sqrt function. A suggested solution involves using MakeExpression to redefine how Mathematica interprets the √ symbol, allowing it to utilize the custom behavior. Additionally, there are warnings about the risks of globally overwriting built-in functions, as this could lead to unexpected bugs in other algorithms. The user acknowledges this advice and considers creating a separate function instead of altering the built-in one.
guerom00
Messages
90
Reaction score
0
Hello all :)

I would like to redefine the built-in square root function.
I have written this :

mySqrt[z_]:=√z;
Unprotect[Sqrt];
Sqrt[z_]:=If[Re[mySqrt[z]]+Im[mySqrt[z]]>0,mySqrt[z],-mySqrt[z]];
Protect[Sqrt]

This works fine and redefine Sqrt[] as I want it to be. But, the symbol √ (by typing Ctrl-2) still points to the original Sqrt[] function ! How can I redefine the behavior of the symbol √ ?

TIA :)
 
Physics news on Phys.org
guerom00 said:
Hello all :)

I would like to redefine the built-in square root function.
I have written this :

mySqrt[z_]:=√z;
Unprotect[Sqrt];
Sqrt[z_]:=If[Re[mySqrt[z]]+Im[mySqrt[z]]>0,mySqrt[z],-mySqrt[z]];
Protect[Sqrt]

This works fine and redefine Sqrt[] as I want it to be. But, the symbol √ (by typing Ctrl-2) still points to the original Sqrt[] function ! How can I redefine the behavior of the symbol √ ? :)

To introduce your own behaviour for complex inputs, you need to change the way that Mathematica parses input expressions. Try replacing your first definition with

Code:
MakeExpression[SqrtBox[expr_], form_] := 
 With[{mexpr = ReleaseHold@MakeExpression[expr, form]}, 
  Hold[mySqrt[mexpr]]]

As an aside, it's not normally a good idea to globally overwrite built-in functions.
Sqrt[] could be used inside many algorithms that will then break - causing hard to track down bugs. Best to just Block[] the symbol when you want to overwrite the normal definition.
 
Thank you for your answer, I'll try that.
And thanks for your warnings : I better define my own square root function and leave the built-in one untouched :)
 

Similar threads

Replies
1
Views
2K
Replies
3
Views
4K
Replies
3
Views
3K
Replies
3
Views
2K
Replies
15
Views
2K
Replies
7
Views
3K
Back
Top