Without actually testing it myself I would make the comment that with Heron's Algorithm it would be better to finish the repeat..until loop when abs(check-xo)<some small tolerance value as otherwise it could loop indefinitely for some values.
Code archives/Algorithms/mathematical algorithms
This code has been declared by its author to be Public Domain code.
Download source code
| some mathematical algorithms |
Here are some of my collections: this is the 'heron-algorithm' with which you can get the square root from 'n' Function Sqr#(n#) x0#=1 repeat check#=0.5*(x0#+n#/x0#) x0#=x1# until check#=x0# return x0# end function this function is to get the greatest common divisor: Function gcd(A,B) While B > 0 R=A mod B A=B B=R Wend Return A End Function this function is to get the least common denominator and based on the gcd function Function lcd(A,B) C=(A*B)/gcd(A,B) Return C End Function to get the factorial of a number you can use this Function fac(n) check=1 For i=1 To n check=check*1 Next Return check Emd Function this function is to get the binomial coefficient, this is to get the number of Pascal's triangle (n choose k) Function nCk(n,k) Return Fac(n)/(Fac(k)*Fac(n-k)) End Function so that's it! I hope it's useful and sorry for my bad english^^ |
Comments
Sometimes you have to be careful with integer arithmetic as well.
With large numbers A*B can 'overflow'. Here is an example of the problem and a corrected lcd().
With large numbers A*B can 'overflow'. Here is an example of the problem and a corrected lcd().
big1 = 100000 big2 = 150000 Print gcd(big1, big2) Print lcd(big1, big2) Print lcd2(big1, big2) WaitKey Function gcd(A,B) While B > 0 R=A Mod B A=B B=R Wend Return A End Function Function lcd(A,B) C=(A*B)/gcd(A,B) Return C End Function Function lcd2(A,B) Return A * ( B / gcd(A,B) ) End Function
Function fac(n)
check=1
For i=1 To n
check=check*1
Next
Return check
Emd Function
;should be
Function fac(n)
check=1
For i=1 To n
check=check*n
Next
Return check
End Function
check=1
For i=1 To n
check=check*1
Next
Return check
Emd Function
;should be
Function fac(n)
check=1
For i=1 To n
check=check*n
Next
Return check
End Function
That works for me... factorial isn't really defined for negative numbers.