PDA

View Full Version : [Request] Mod Funcion between two extended values?



sesillabubu
08-07-2011, 07:20 PM
How is possible to have mod value from extendes values?

Thanks
Sesilla

Dan
09-07-2011, 02:19 AM
I think you mean "extendeds" and it isn't possible=)

WILL
09-07-2011, 03:47 AM
var floating_point_variable: Extended; It just stores a more accurate Real variable.

User137
09-07-2011, 09:58 AM
Maybe something like this:

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;
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.

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...

User137
09-07-2011, 11:43 AM
Well this issue got my interest really... There is a function for C++, called fmod() http://pubs.opengroup.org/onlinepubs/007908799/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:

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;
Result will always be positive this way, which is how i guess modulus should be. So that simplified code a bit.
Using pascal way of having result variable made me get rid of c: Extended.

Dan
09-07-2011, 03:06 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:


function fmod(const a, b: Single): Single; inline;
begin
Result := a - Int(a / b) * b;
end;


replace Single with Extended if you have to=)

User137
09-07-2011, 08:19 PM
That will work. I wasn't aware of Int() function but it seem to do just the wanted thing by docs.