MATLAB: Problem using factorial in matlab

factorials

I wanted to calculate 200! but after 170! matlab starts showing result NaN. So is there any way possible to calculate this number using matlab???

Best Answer

You cannot solve it with a double precision result, because it will overflow the dynamic range of a double.
factorial(200)
ans =
Inf
But if you are willing to use other tools, there is no problem. For example, the symbolic toolbox gives you this:
factorial(sym(200))
ans =
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
Or, my own vpi toolbox , found on the file exchange:
factorial(vpi(200))
ans =
78865786736479050355236321393218506229513597768717326329474253324435
944996340334292030428401198462390417721213891963883025764279024263710506
192662495282993111346285727076331723739698894392244562145166424025403329
186413122742829485327752424240757390324032125740557956866022603190417032
406235170085879617892222278962370389737472000000000000000000000000000000
0000000000000000000
In either case, the result is an integer with almost 400 digits.
If you are happy with a floating point number, use my HPF toolbox . So in 50 digits of precision...
factorial(hpf(200,50))
ans =
7.8865786736479050355236321393218506229513597768717e374
Remember that any such high precision computation will be far less efficient than using a double. You are almost always better off using good numerical methods to avoid the problem in the first place. But that is why they teach entire courses about such methods, and books are written on the topic.