[Mathematica] Redefining a built-in symbol

  • Mathematica
  • Thread starter guerom00
  • Start date
  • #1
guerom00
93
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 :)
 

Answers and Replies

  • #2
Simon_Tyler
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
guerom00
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 :)
 

Suggested for: [Mathematica] Redefining a built-in symbol

Replies
1
Views
188
Replies
6
Views
425
Replies
5
Views
546
Replies
0
Views
148
Replies
1
Views
211
Replies
6
Views
3K
Replies
1
Views
638
  • Last Post
Replies
1
Views
537
Replies
2
Views
246
  • Last Post
Replies
5
Views
265
Top