develooper Front page | perl.perl5.porters | Postings from October 2003

Re: [perl #24091] Not OK: perl v5.8.1 on sgi6-irix-ld 6.5

From:
Ed Allen Smith
Date:
October 7, 2003 16:17
Subject:
Re: [perl #24091] Not OK: perl v5.8.1 on sgi6-irix-ld 6.5
Message ID:
mid+200310072317.h97NHCI71164750@dogberry.rutgers.edu
In message <20031007225502.GA732@efn.org> (on 7 October 2003 15:55:03
-0700), sthoenna@efn.org (Yitzchak Scott-Thoennes) wrote:
>On Tue, Oct 07, 2003 at 06:33:33PM -0400, Ed Allen Smith
><easmith@beatrice.rutgers.edu> wrote:
>> 
>> I'll change my earlier suggestion of how to handle this in Math::BigInt. I
>> suggest changing the current code in _root from:
>> 
>>       # fit's into one Perl scalar, so result can be computed directly
>>       $x->[0] = int( $x->[0] ** (1 / $n->[0]) );
>> 
>> to:
>> 
>> 	if ($x->[0] == 0) {
>> 	   return 0;
>> 	}
>> 	# fits into one Perl scalar, so result can be computed directly
>> 	my $temp = $x->[0] ** (1 / $n->[0]);
>> 	my $a = int($temp);
>> 	my $b = int($temp + (($temp > 0) ? 0.5 : -0.5));

The (($temp > 0) ? 0.5 : -0.5) isn't necessary if Calc.pm is always fed
positive integers as $x->[0], BTW.

>> 	if ($a == $b) {
>> 	   $x->[0] = $a;
>> 	} elsif (abs(($a**$n->[0]) - $x->[0]) > abs(($b**$n->[0]) - $x->[0])) {
>> 	   $x->[0] = $b;
>> 	} else {
>> 	   $x->[0] = $a;
>> 	}
>> 	return $x;
>> 
>> In other words, if adding 0.5 (equivalently, subtracting, if the result
>>is negative) will give a more arithmetically correct result after
>>truncating, do it; otherwise, don't. (It's likely that the same sort of
>>thing would be helpful for the _sqrt function.)
>
>That's basically just a form of rounding, only not based on just
>rounding the result.

Correct. It's choosing whether to truncate, or to round .5 and up upward. 

>It looks more to me as if the goal here is to
>come up with the greatest result $a such that $a**$n->[0] <= $x->[0]

I can see that argument; it depends on whether one wishes to stick with
Calc.pm always truncating to int in _root or not.

>(not sure if that "greatest" or "<=" is meant to apply to absolute
>values or not).
>
>But your general method certainly works for that.

There are some cases in which the above would be different (none for what
"should be integers", but if the result before truncating has a .5 or higher
after the decimal point, it could round up instead of truncating, if that
gives a more arithmetically correct result). I can see arguments for going
either way.

     -Allen

-- 
Allen Smith			http://cesario.rutgers.edu/easmith/
September 11, 2001		A Day That Shall Live In Infamy II
"They that can give up essential liberty to obtain a little temporary
safety deserve neither liberty nor safety." - Benjamin Franklin



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About