Exact square root aretmetic

Hi,
is it possible to use square root of something that is not possible to evaluate exactly as a symbol and to not evaluate it.
For example square root of 2 times square root of 2 is not 2:

julia> √2^2 == √2*√2
false
julia> √2*√2
2.0000000000000004

is there something similar to the fraction operator (‘//’)?
I’m happy if my result has a √2 in it.

I tried to use the sympy package as well but I couldn’t find a way to do it correctly.

Is there something I missed?

1 Like

Well this is something that is always going to be a problem with floating point numbers. In fact, the square root of 2 is irrational, so no decimal will do it exactly. So one thing you need to ask is, does it actually need to be exact? Anything that will handle this exactly will be much slower (for many reasons), so you really need to make sure “that you need it”.

In SymPy you just take the squareroot of an expression. If you have a symbol x, and you just y=sqrt(x). Then you have a new expression for the squareroot of x. When you input 2, that will give you something that the computer can write down as the square root of 2. But remember, it can never store that decimal because… well… it’s infinite.

You can create your own Irrational by giving a function which generates the square root of two. That’s how pi is implemented. But that’s likely more difficult than you need.

Lastly, there’s this algebraic number system in Julia:

https://github.com/anj1/AlgebraicNumbers.jl

But note, algebraic numbers will explode in complexity as you do operations, so their usage is limited.

But why do you need "exact square root"s? Likely you want to modify your problem if that’s what you’re looking for.

1 Like

thank you for the fast answer.
I’m aware of floating point arithmetic and I totally see the point.

What I want to do is some symbolic arithmetic using the sympy package. I want to creating some combination of various polynomials and extract the monomials in them …
And there fore I want to stay with √2, √3 ,… and do not evaluate them.
I was not able to find how to do this in julia

But you help me

julia> @syms x
(x)
julia> sq=sqrt(x)
√x
julia> sq(2)
√2

does the trick. It is not so nice to write it down but I can deal with it now.
Thank you.

Or use sqrt(Sym(2)) directly