[Mathematica] Redefining a built-in symbol

  • Mathematica
  • Thread starter guerom00
  • Start date
  • #1
93
0

Main Question or Discussion Point

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 :)
 

Answers and Replies

  • #2
313
1
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.
 
  • #3
93
0
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 :)
 

Related Threads on [Mathematica] Redefining a built-in symbol

Replies
5
Views
4K
Replies
5
Views
4K
Replies
1
Views
2K
Replies
3
Views
4K
Replies
0
Views
2K
Replies
3
Views
3K
  • Last Post
Replies
5
Views
2K
Top