Internet PLC Forum
General => Technical support => Topic started by: Santiago Garza on November 25, 2005, 10:47:03 AM
-
Hi. I am trying to do a program where I need to use the circle equation.
I couldnt find the square root function and how to write a square number either.
Can you help me?
thank you
-
The PLC does not support floating point so Square root function are not supported. For limited range of value you could pre-store the data in DM and use the index to find the corresponding value. This is called a look-up table.
-
I came across the same problem when having to calculate real time RMS currents and got a reasonable solution by using a technique called "newton's iteration" - here is a link that describes the technique - http://www.jimloy.com/arith/sqrt.htm
For my purposes it was not too computationally intensive and I got a pretty good estimate in 5 to 7 iterations.
Bruce
-
I haven't tried to compare but the method I've used in the past uses a multiply instead of divide per iteration. It's a simple binary search - If you want a 16 bit result from a 32 bit source then it always takes 15 iterations and is not an estimate so it's as accurate as 16 bits can be. Combined with the multiply, which is often a lot faster than a divide, then the binary search method might be a better solution.
The search loop goes something like:
square=12345678 ' The number we want to find the square-root of.
sqroot=0 ' The resultant square-root.
index = &8000 ' The bit mask indexing.
sqrt_loop:
sqroot = sqroot + index
if sqroot * sqroot > square then sqroot = sqroot - index
index = index >> 1
if index<>0 then sqrt_loop
Evan
-
And if you want rounding to nearest, instead of rounding down, it changes in detail but not really all that much:
square=12345678 ' The number we want to find the square-root of.
sqroot=0 ' The resultant square-root.
index = &8000 ' The bit mask indexing.
check = 0 ' The lookahead sqroot - Added for faster execution.
sqrt_loop:
check = sqroot + index
index = index >> 1
if (check * check - check) < square then sqroot = check
if index<>0 then sqrt_loop
Evan