Yes, I made a mistake. Good catch
it should be n=n+1 and the number should be 17 instead of 18. I was posting too quickly.
What does it do with non-perfect squares? It can't come up with a fractional part. Though that may not be relevant in this case.
Not a problem. The square root of twenty is done like this
N=20*100
The answer is
r=sqrt(20)*sqrt(100) or sqrt(20)*10
So
N=2000
the square root of 2000 is 45 but now this must be divided by 10 to get the answer 4.5
I can also multiply by 10000 before the square root and divide by 100 after wards.
One our second generation, integer only, motion controller I multiplied the the integer by 65536 and took the square root. The square root of a 32 bit number is a 16 bit number but since I multiplied by 65536 before the square root, I must divide by 256 after the square root. Actually I simply used the integer in the high byte and the fraction of 256 in the lower byte.
I didn't use the 1,3,5,7 approach. I used a look up table to calculate the most significant byte of the square root. I then did one iteration using Newton's method. Since Newton's methods doubles the number if accurate bits only one iteration is required to get a 16 bit result.
I wouldn't use Newton's method on a integer only PLC. If one needs the answer that quickly then get a PLC with the square root built in.
The Newton method would return a fractional part but needs REAL math and has divides so much slower with the same processor.
You can't believe how much time I have spent optimizing the real sqrt(). No division is necessary. I have done the same for cbrt() or cube root too but that requires a divide.
BTW, the 1,3,5,7,.... technique is how the HP35 did square roots.