3

For example, I want to covert y + Sqrt[x] to y + x^0.5, where y and x can be very complicated expressions.

Edit: Here's why I want to do this. I want to generate C++ expression from Mathematica expression. The method I can think of is to do some sort of recursion down the expression tree. I don't want to have things like 1/2 or 2/3 anywhere in the expression (but rather, 0.5 or 0.66666666666666667 is fine). However, the function N doesn't apply to the exponent.

Moreover, if this walking down the expression tree can recognize Sqrt, it would be even better. However, Head[Sqrt[x]] is Power, not Sqrt.

Edit: Problem solved: use SymbolicC`CExpression and SymbolicC`ToCCodeString, together with some macros.

MarcoB
  • 67,153
  • 18
  • 91
  • 189
Xiao Feng
  • 31
  • 4
  • 1
    While it's possible to do, you'd probably get more useful responses if you explained why you want to do this. – Szabolcs Jan 02 '15 at 20:53
  • 2
    Your title has nothing to do with your question. What are you asking here? – David G. Stork Jan 02 '15 at 21:20
  • possible dup http://mathematica.stackexchange.com/questions/48869/use-only-exponents-no-radicals-in-output-expressions – george2079 Jan 02 '15 at 21:33
  • Be aware introducing the floating point 0.5 changes an exact expression into one that is considered to be approximate. The linked question addresses the display formatting which is probably what you really want. – george2079 Jan 02 '15 at 21:55
  • Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. – bbgodfrey Jan 02 '15 at 22:22
  • To give an example related to @george2079's comment, note that for a symbolic x, (x^0.5)^2 == x does not evaluate to True, and even evaluates to False on some numeric input (e.g. x -> I). – Michael E2 Jan 02 '15 at 22:22
  • 你的问题和N完全无关啊?N不会把Sqrt[x]变成x^(0.5) – Chen Stats Yu Jan 02 '15 at 23:21
  • N[6/5*(3+x)] gives 1.2(3.+x). Something is holding the same conversion for the exponent in, say, Power[x, 3/2]. I want to know how to turn that off. – Xiao Feng Jan 02 '15 at 23:30
  • One possibility is to use SetPrecision[expr,MachinePrecision] on your expression. – Daniel Lichtblau Jan 03 '15 at 21:03

1 Answers1

2

Use the substitution rule as follows:

myExpression /. Sqrt[x___] -> x^0.5

Example:

myExpression = Cos[t] + Sin[y] + Sqrt[a y + Tanh[z] + u^3]

Cos[t] + Sin[y] + (u^3 + a y + Tanh[z])^0.5

David G. Stork
  • 41,180
  • 3
  • 34
  • 96