# How do I write Sqrt[x] as x^(1/2)

Sometimes it is needed to keep the powers as the fractional form. However Mathematica tends to write x^(1/2) as Sqrt[x].

How do I keep x^(1/2) as it is in the output without writing it as Sqrt[x]?

Here is a simple example:

 expr = Rationalize[1+x^(0.5),0.0000001] >> output.m


Output is

 1 + Sqrt[x]


Instead I want the output to have the form

 1 + x^(1/2)


I could not find any solution for this.

• 1 + x^(1/2) /. Sqrt[z_] :> z^HoldForm[1/2] is close. You would need to ReleaseHold to do much with it. – Bob Hanlon Mar 4 at 16:19
• It occured to me as well. But since this is at the output level (i.e. this expression is going to be saved in an output file), I can not use ReleaseHold before. For me then easiest way is to manipulate the expression in the output file by other means. But I hope there must be some better ways to do it in Mathematica itself. – Boogeyman Mar 4 at 16:23

Put (the FullForm for >>) uses InputForm to write expressions to the file. So, one idea is to modify the InputForm rules temporarily:

Unprotect[Power];
Format[Power[x_, 1/2], InputForm] /; $Sqrt := Power[x, SequenceForm[1]/2] Protect[Power];  SequenceForm is a special wrapper that is not visible inside InputForm. By including the wrapper SequenceForm around the 1, the Sqrt rewriting rule doesn't fire. Wrapping SequenceForm around the 1/2 won't work because then no parentheses will be used to wrap the exponent. Then, blocking $Sqrt to True will cause the new format to be used:

Block[{\$Sqrt = True}, Put[1 + Sqrt[x], "tmp.m"]]


Check:

Import["tmp.m","String"]


"1 + x^(1/2)"

• Thanks. What about other export methods like WriteString ? Currently I am trying to export a list {1,2,x^(1/2)} as Text/String like WriteString["tmp.m",ExportString[{1,2,x^(1/2)},"Text"] ]. I have to adopt similar methods? Basically it seems that there is no straightforward way to implement it globally within Mathematica. What is it so special about Sqrt, other powers are written as it is except for 1/2 which is always translated to Sqrt. :-/ – Boogeyman Mar 4 at 18:22
• @Boogeyman The same method works for Export to "Text". – Carl Woll Mar 4 at 18:46
g=x^(1/2)/. Rational[1,2]->Defer[1/2];
expr = Rationalize[1 + g, 0.0000001] >> output.m

<<output.m


WriteString["tmp.m", ExportString[{1,2,g},"Text"]]

<<tmp.m


As mentioned in the comments, the files created above contain x^Defer[1/2]. If the goal is to get a text file with x^(1/2), then it can be created from the original output file:

WriteString["outputNew.m",
StringReplace[Import["output.m", "Text"], "Defer[1/2]" -> "(1/2)"]]

• In output.m, I get 1 + x^Defer[1/2], not 1 + x ^(1/2). What do you get? – Michael E2 Mar 5 at 13:32
• Correct. The file still carries the Defer. – Jean-Pierre Mar 5 at 13:38