Why doesn't Matlab's answer to factorial(100) equal Wolfram Alpha's 100!?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alok Virkar
el 24 de Oct. de 2017
When computing:
>> a = sprintf('%f',factorial(100))
a =
'93326215443944102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000'
However the number above does not equal 100!
why is this and how do I fix it?
2 comentarios
Respuesta aceptada
Andrei Bobrov
el 24 de Oct. de 2017
factorial(sym(100))
3 comentarios
Walter Roberson
el 24 de Oct. de 2017
sym(factorial(100)) calculates factorial(100) in double precision and passes the result to sym(), which then converts that rather wrong double precision number to an extended precision number.
Remember, in MATLAB, arguments are always evaluated before being passed to a function.
The only exception to this that I can think of is that the various int*() and uint*() and single() and double() calls with a literal number (and spacing is important!) is treated as syntax rather than a function call: those restricted cases of using those functions create the values at parse time rather than at execution time. This was needed to be able to write a accurately write integers between 2^53 and 2^64-1.
Más respuestas (2)
Walter Roberson
el 24 de Oct. de 2017
Two reasons:
1) You are using MS Windows, and the native number formatting routines cannot handle more than 16 digits. On OS-X / MacOS, which does the conversion properly,
>> a = sprintf('%f',factorial(100))
a =
'93326215443944102188325606108575267240944254854960571509166910400407995064242937148632694030450512898042989296944474898258737204311236641477561877016501813248.000000'
If I recall correctly, Linux does better than MS Windows but not as good as Mac.
2)
>> eps(factorial(100))
ans =
1.21943302746718e+142
By that large of a number, the distance between representable numbers is large enough integers as to badly distort the value.
Work around:
>> factorial(sym(100))
ans =
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
WEEKIAN SOH
el 26 de Feb. de 2018
Indeed this is a good question. I had also noticed the same problem while I compare Mathematica's factorial(100) with Matlab's.
Good thing we don't have to work with so large of a numbers most of the time...
Now, if I want high precisions to see the digits, I'll use sym(Number), and pass this sym(Number) into the function to derive the long precisions.
Thank you for sharing the answer
0 comentarios
Ver también
Categorías
Más información sobre Startup and Shutdown en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!