How is possible to have mod value from extendes values?
Thanks
Sesilla
How is possible to have mod value from extendes values?
Thanks
Sesilla
Maybe something like this:
But as you can see it can be a slow function if difference in numbers is big. Try this with A 100000 and B 0.00001 and you know what i mean... Also the more time it takes the more inaccurate the result may be.Code:function ModExt(a, b: Extended): Extended; var a_negative, b_negative: boolean; begin if b=0 then begin // This would otherwise make endless loop result:=0; exit; end; a_negative:=a<0; b_negative:=b<0; result:=abs(a); b:=abs(b); while result>=b do result:=result-b; if a_negative then result:=-result; if b_negative then result:=-result; end;
edit #6?: Oops, result-b, not result/b
Not satisfied with those negative counts still... Because of (result>b) both of them must be abs()'d. But also if both would be negative then negatives would cause positive total effect. I had 1 variable version on earlier edit but cba now... This function is close to useless anyway.
Hmm, could optimize with division me thinks...
Last edited by User137; 09-07-2011 at 11:22 AM.
Well this issue got my interest really... There is a function for C++, called fmod() http://pubs.opengroup.org/onlinepubs.../xsh/fmod.html
Some sort of formula suggestions so far are:
a - b*trunc(a/b) <-- This works but is limited within integer range
or
a/b - floor(a/b) <-- Doesn't give a valid result
Pascal math unit doesn't have this function.
Edit: Propably my final answer The formula was good but by replacing Trunc() with non limited code it should work properly:
Result will always be positive this way, which is how i guess modulus should be. So that simplified code a bit.Code:function ModExt(a, b: Extended): Extended; begin if b=0 then begin // Prevent division by zero result:=0; exit; end; a:=abs(a); b:=abs(b); result:=a/b; result:=a-b*(result-frac(result)); end;
Using pascal way of having result variable made me get rid of c: Extended.
Last edited by User137; 09-07-2011 at 12:11 PM.
ah... I see what you are trying to do. this will do the trick for both positive and negative numbers, and will throw a div by 0 exception when appropriate:
replace Single with Extended if you have to=)Code:function fmod(const a, b: Single): Single; inline; begin Result := a - Int(a / b) * b; end;
Last edited by Dan; 09-07-2011 at 03:09 PM.
That will work. I wasn't aware of Int() function but it seem to do just the wanted thing by docs.
Bookmarks