user10607
user10607

Reputation: 3071

Get matlab to show square roots (i.e. 2^(1/2) instead of 1.414)

I have a few simple equations that I want to pipe through matlab. But I would like to get exact answers, because these values are expected to be used and simplified later on.

Right now Matlab shows sqrt(2.0) as 1.1414 instead of something like 2^(1/2) as I would like.

I tried turning on format rat but this is dangerous becasue it shows sqrt(2) as 1393/985 without any sort of warning.

There is "symbolic math" but it seems like overkill.

All I want is that 2 + sqrt(50) would return something like 2 + 5 * (2)^(1/2) and even my 5 years old CASIO calculator can do this!

So what can I do to get 2 + sqrt(50) evaluate to 2 + 5 * (2)^(1/2) in matlab?

Upvotes: 1

Views: 7662

Answers (2)

Oleg
Oleg

Reputation: 10676

Matlab main engine is not symbolic but numeric.

Symbolic toolbox. Create expression in x and subs x = 50

syms x
f = 2+sqrt(x)

subs(f,50)
ans =
50^(1/2) + 2

Upvotes: 3

Adriaan
Adriaan

Reputation: 18187

As per @Oleg's comment use symbolic math.

x=sym('2')+sqrt(sym('50'))
x =
5*2^(1/2) + 2

The average time on ten thousand iterations through this expression is 1.2 milliseconds, whilst the time for the numeric expression (x=2+sqrt(50)) is only 0.4 micro seconds, i.e. a factor of ten thousand faster.

I did pre-run the symbolic expression 50 times, because, as Oleg points out in his second comment the symbolic engine needs some warming up. The first run through your expression took my pc almost 2 seconds.

I would therefore recommend using numeric equations due to the huge difference in calculation time. Only use symbolic expressions when you are forced to (e.g. simplifying expressions for a paper) and then use a symbolic computation engine like Maple or Wolfram Alpha.

Upvotes: 8

Related Questions