Re: computing 20! all the way
Re: computing 20! all the way
- Subject: Re: computing 20! all the way
- From: Christopher Nebel <email@hidden>
- Date: Fri, 12 Nov 2004 09:14:01 -0800
On Nov 12, 2004, at 8:44 AM, Courtney Schwartz wrote:
On Nov 12, 2004, at 11:09 AM, Doug McNutt wrote:
At 17:37 +1100 11/12/04, Richard Morton wrote:
on factorial from n
if n = 0 then return 1
return n * (factorial from (n - 1))
end factorial
That recursion is a good example of a technique that is useful for
such things as traversing a directory tree in AppleScript but it
won't solve the underlying question of this thread which is that IEEE
floating point doubles (64 bits) simply will not support more than
approximately 15 decimal digits of precision. One needs type extended
(80 bits) which AppleScript will not do and it won't take much above
20! to exceed even that.
Character based techniques, as suggested by others, for arbitrary
precision are probably best for such things but they are slow.
:: digs through the language guide::
What about the data type Data? Would that work for this sort of thing?
Not in the slightest. "Data" is just anonymous data; there are no
operations defined on it. I seem to have missed the OP, so I suspect
I'm repeating something here, but what Mr. McNutt means is that the
answer in AppleScript will only be approximate, since doubles only have
limited precision -- 54 binary digits, or about 15 decimal ones. (In
fact, the answer for 20! will be accurate, because it while it's 19
digits long, the last four are zero. 21! would not be, however.)
The easiest way to get an exact answer (though of course you have to
deal with it as a string) is to shell out to some language that has
what's canonically known as "bignum" support, aka arbitrary precision
numbers. For example:
on factorial(x)
-- all one line...
return do shell script "perl -e 'use bigint; sub f($) { my $x =
shift; return $x <= 1 ? 1 : $x * f($x - 1); } print f(" & x & ")'"
end factorial
factorial(20) --> "2432902008176640000"
factorial(100) -->
"93326215443944152681699238856266700490715968264381621468592963895217599
993229915608941463976156518286253697920827223758251185210916864000000000
000000000000000" (wheee!)
--Chris Nebel
AppleScript Engineering
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Applescript-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden