|
Post by wybiral on May 9, 2006 22:43:53 GMT -5
Heres a code to find the approximate square root of a number... Naturally, this code makes no sense since there is a squareroot function in basic4gl that is probably faster and more accurate... But, why not... lol. Yes, I know... I am the king at wasting my own time...
dim a# dim b# dim c# c#=.025 input "Enter number to find square root: ", a# b#=(a#/2) do b#=b#-c#
if b#<0 then b#=(a#/2) c#=c#/1.75 endif
loop until val(left$(str$(a#),6))=val(left$(Str$(b#*b#),6)) printr b#
|
|
|
Post by kronos on May 13, 2006 6:54:47 GMT -5
It's always best to try and avoid the square root function in your code though isn't it, as it's rather intensive.
|
|
|
Post by wybiral on May 13, 2006 14:59:05 GMT -5
Yeah, the research I've done says that it is usually a similar algorithm... Kindof a hit and miss, until b * b equals a. So yeah, very time consuming... I guess sine and cosine can be too, although I use them alot with very little decrease... Who knows. You can usually optimize things until the run better anyway... Unless you write it PERFECT the first time, but thats just crazy talk.... (I end up rewriting my code SEVERAL times before I am content)
|
|
|
Post by kronos on May 14, 2006 6:02:12 GMT -5
Indeed..next time you are doodling howzabout a cube root function?
|
|
|
Post by wybiral on May 14, 2006 15:37:42 GMT -5
dim a# dim b# dim c#
c#=.025
input "Enter number to find square root: ", a#
'Find cube root b#=(a#/4) do b#=b#-c# if b#<0 then b#=(a#/4): c#=c#/1.75 endif 'Increase sensitivity becasuse we skipped the number loop until val(left$(str$(a#),6))=val(left$(Str$(b#*b#*b#),6)) 'When b#*b#*b#=a#, then b# is the cube root
printr b#
That should give you the cube root. The theory here is that the cube root is going to be less than 1/4 of the number we are finding it for. Then, we start at the 1/4 point and move down to zero using c# units each movement... If we make it to zero without b#^3 equaling a#, then we skipped it, so... We reduce the value of c# to increase sensitivity and do it again... We keep doing this until b#^3 equals a#, meaning b# is the cube root of a#. It will work for most smaller numbers, but the larger you get, the slower it will be. This could DEFINITELY be improved, I just kindof made this up, so it needs to be fine tuned... It works though, thats a plus.
|
|