HI all,
I try this:
sqrt(1)
why it only returns 1.0
not +1
and -1
?
How to get all the roots? Which packages to use?
Thanks.
HI all,
I try this:
sqrt(1)
why it only returns 1.0
not +1
and -1
?
How to get all the roots? Which packages to use?
Thanks.
sqrt(x)
necessarily returns a Float type as not every number is a perfect square. If you want to return an Integer without concerning oneself with loss of precision, you can do trunc(Int, sqrt(x))
.
In this instance, it would personally seem redundant to return a Tuple showing the exact opposites of the same number as every number except 0 has both a positive and negative square root . There is a good discussion about this topic on mathematics stack exchange.
You can write your own square root function:
# keep Float type
function square_root(x)
return (sqrt(x), -sqrt(x))
end
# allow for loss of precision by returning as an Integer
function square_root_trunc(x)
truncated_result = trunc(Int, sqrt(x))
return (truncated_result, -truncated_result)
end
For integer input you also have isqrt
, which should avoid rounding errors.
It is really amazing and works great this is the full code for anyone who want:
using SymPy
x = symbols("x")
# To calculate the integral between interval [-2,2]
fc = integrate(abs(x), (x, -2, 2))
# keep Float type
function square_root(x)
return (sqrt(x), -sqrt(x))
end
# allow for loss of precision by returning as an Integer
function square_root_trunc(x)
truncated_result = trunc(Int, sqrt(x))
return (truncated_result, -truncated_result)
end
# Find the values of c that satisfy the Mean Value Theorem for Integrals
# since f(x) = |x|, then f(c) = |c|
c = fc/(2-(-2))
println("f(c) = |c| = ", c)
println("c = ", square_root(c))
As for the ±, that is just the definition of the square root. That is, while (-1)^2 = 1
, \sqrt{1} = +1
.