[SOLVED] Gnuplot factorial calculation output


I wanted to test a recursive function in gnuplot.
The following is the function

factorial(n)= ((n==1?sprintf("1"):sprintf("%f",n*factorial(n-1))))

when factorial(100) tested, it looks fine


to make the number a integer, i changed sprintf like that

factorial(n)= ((n==1?sprintf("1"):sprintf("%d",n*factorial(n-1))))

But, the result is strange ; it seemed to be out of range on integer size?


So i changed the function on real number type without no number below floating point

factorial(n)= ((n==1?sprintf("1"):sprintf("%.0f",n*factorial(n-1))))

But, the result is more strange,


Could u explain what it is?


The largest integer that can be represented in 32 bits is 2147483647.
So a 32-bit integer (gnuplot through version 5.2) runs out of bits between 12! and 13!

A 64-bit integer (gnuplot 5.4) runs out of bits between 20! and 21!

If you use double precision floating point arithmetic it can hold larger numbers, but the number of bits still limits the precision. 64-bit floating point has only ~53 bits of precision, so the largest exact factorial it can represent is actually smaller than can be handled by a 64-bit integer.

Note that all of your example gnuplot code uses integer arithmetic if n is an integer. Changing to a floating point format for printing doesn’t change that.

Answered By – Ethan

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.