Topic : STM8 - Ride7 - Integer Sqrt

Forum : ST7/STM8

Original Post
Post Information Post
June 6, 2012 - 9:35am


I need a square root function which can deal with integers. So I used the usual sqrt function of Math.h. I tested it with some integer values, and casted into integers (usually the function takes double as argument and returns a double). The results were the followings:
Is there a way to get exact values for integers?

Thanks for you anwers!

Post Information Post
June 15, 2012 - 9:16am

This is the usual rounding error when dealing with floating point numbers.
You could use something like (int) (sqrt(fnum) + 0.5)

> Is there a way to get exact values for integers?

The result of the square root is, in the mathematical sense, only in some rare cases in integer, so you loose precisision anyway. Assuming you name your function isqrt(), you have for instance:
isqrt(9) = isqrt(10) = isqrt(11) = isqrt(12) = isqrt(13) = isqrt(14) = isqrt(15) = 3
It's ok if you can live with that.

Floating point calculations are not fast on an 8 Bit controller, and pull in a lot of bulky library function.
You can create constant table, and interpolate. This is often done for having a fast integer - sin()/cos().