Couple of other maths routines

Previous topic - Next topic

MrTAToad

Again, this is converted from my DBPro.  These contain the value of pi, pi2, factorial and compares two floating point values.

Test code :

Code (glbasic) Select
DEBUG PI()+"\n"
DEBUG PHI()+"\n"
DEBUG PHI2()+"\n"
DEBUG "Factorial : "+factorial(4)+"\n"
DEBUG "Compare : "+fcmp(1.0001,1.0005,0.0001)+"\n"


Code (glbasic) Select
FUNCTION PI:
RETURN 3.14159265358979
ENDFUNCTION

FUNCTION PHI:
RETURN 1.6180339887
ENDFUNCTION

FUNCTION PHI2:
RETURN 0.6180339
ENDFUNCTION

FUNCTION factorial%:value%
LOCAL total%

IF value%<=1
total%=1
ELSE
total%=value%
ENDIF

WHILE value%>1
total%=total%*(value%-1)
DEC value%,1
WEND

RETURN total%
ENDFUNCTION

FUNCTION fcmp%:value1,value2,epsilon
IF ABS(value1-value2)<=ABS(value1)*epsilon
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION

Quentin

thanks, could be useful.

What is funciton fcmp% meant for? Could you please give a small example?

MrTAToad

FCMP% is used to compare two floating-point values to within a certain tolerance.  This is because, as a floating-point value may not be stored how you would like/think it is, doing a standard

Code (glbasic) Select

if a=b
..
endif


may or may not work.

Thus, if we compare to a certain number of decimal places we will know if two values are approximately the same or not.

Code (glbasic) Select

DEBUG "Compare : "+fcmp(1.0001,1.0005,0.0001)+"\n"


compares 1.0001 and 1.0005 to 4dp - in this case they are more or less the same.