>I recently came across the need to do a financial calculation that cannot be handled Algebraically. IOW, the only way to find the correct number is to guess the answer and work backwards. The math is easy. But the "guessing" algorithm turned out to be be a very interesting piece of code, and I am curious if my solution was the standard way of handling things. I am also interested to see how you might have handled it.
>
>My particular problem was far too complex to make a challenge of, but I can give a very simple riddle whose solution would need to use the same principles...
>
>Write a function to calculate the square root of a number to a given number of decimal places. (Yes. I know, VFP has the SQRT function, but what would you do without it?)
Ok, you got me interested so see if this is what you thought you would get.
paramters lnval,lnplaces
set decimals to lnplaces
lnnext = lnval/2
lnsmaller = 0
lnbigger = 2*lnval
lldone = .f.
do while !lldone
do case
case round(lnnext*lnnext,lnplaces) > lnval
lnbigger = lnnext
lnnext = lnnext - ((lnnext - lnsmaller)/2)
case round(lnnext*lnnext,lnplaces) < lnval
lnsmaller = lnnext
lnnext = lnbigger - ((lnbigger - lnnext)/2)
otherwise
lndone = .t.
endcase
enddo
return lnnext
Previous
Next
Reply
View the map of this thread
View the map of this thread starting from this message only
View all messages of this thread
View all messages of this thread starting from this message only