Re: simple eurphoria question

new topic     » goto parent     » topic index » view thread      » older message » newer message

Larry Miller wrote:
> 
> This function will find the integer portion of a negative number - most of the
> time:
> 
> }}}
<eucode>
> if integer(x) then
>      return x
> elsif x<0 then
>      return floor(x+1)
> else
>      return floor(x)
> end if
> 
> </eucode>
{{{

> 
> The problem is that integer(x) will return 0 for any number outside of
> Euphoria's
> integer range, even if it has no fractional component. The function above when
> used with -4000000000 will return -3999999999, which is wrong.
> 
> This method is used in Ricardo Forno's General function library for
> FloorTowardsZero()
> and probably others. It should be corrected.
> 
> Larry Miller

Yep, you are right.
I performed the following test of candidate good functions for this task.
The results showed all three were correct, but f2 was the fastest:

constant MAX = 50000000
atom t, x


function f1(atom a)
    
    return a - remainder(a,1)
end function

function f2(atom a)
    if a < 0 then
	return - floor(- a)
    end if
    return floor(a)
end function

function f3(atom a)
    atom b
    b = 2 * (a > 0) - 1
    return b * floor(a * b)
end function

t = time()
for i = 1 to MAX do
    x = f1(89.76)
end for
printf(1, "f1 = %f\n", time() - t)

t = time()
for i = 1 to MAX do
    x = f2(89.76)
end for
printf(1, "f2 = %f\n", time() - t)

t = time()
for i = 1 to MAX do
    x = f3(89.76)
end for
printf(1, "f3 = %f\n", time() - t)

printf(1, "0 %f %f %f\n", {f1(0), f2(0), f3(0)})
printf(1, "50 %f %f %f\n", {f1(50), f2(50), f3(50)})
printf(1, "-50 %f %f %f\n", {f1(-50), f2(-50), f3(-50)})
printf(1, "8.76 %f %f %f\n", {f1(8.76), f2(8.76), f3(8.76)})
printf(1, "-8.76 %f %f %f\n", {f1(-8.76), f2(-8.76), f3(-8.76)})
printf(1, "4346567890 %f %f %f\n", {f1(434567890), f2(434567890),
f3(434567890)})
printf(1, "-4346567890 %f %f %f\n", {f1(-434567890), f2(434567890),
f3(-434567890)})
printf(1, "4346567890.67 %f %f %f\n", {f1(434567890.67), f2(434567890.67),
f3(434567890.67)})
printf(1, "-4346567890.67 %f %f %f\n", {f1(-434567890.67), f2(-434567890.67),
f3(-434567890.67)})



So, I'm going to correct genfunc.e
Regards.

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu