# GLBasic forum

## Codesnippets => Math => Topic started by: MrTAToad on 2009-Feb-07

Title: Couple of other maths routines
Post by: MrTAToad on 2009-Feb-07
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.14159265358979ENDFUNCTIONFUNCTION PHI: RETURN 1.6180339887ENDFUNCTIONFUNCTION PHI2: RETURN 0.6180339ENDFUNCTIONFUNCTION 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% ENDFUNCTIONFUNCTION fcmp%:value1,value2,epsilon IF ABS(value1-value2)<=ABS(value1)*epsilon RETURN TRUE ELSE RETURN FALSE ENDIFENDFUNCTION`
Title: Re: Couple of other maths routines
Post by: Quentin on 2009-Feb-07
thanks, could be useful.

What is funciton fcmp% meant for? Could you please give a small example?
Title: Re: Couple of other maths routines
Post by: MrTAToad on 2009-Feb-07
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.