2014-11-06 79 views
0

我正在研究一个MATLAB程序,并想知道如何得到我的返回值,当它显示为Inf(对MATLAB来说太大)。我如何让MATLAB显示一个正在返回的Inf(Infinity)的数字?

% Question2 
% Program is meant to calculate the product of all the odd numbers from 1 to 1000 
% declare variable ‘product’ as zero 
product = 1.; 
% initialize counter, ‘n’, to 1000 
n = 1000; 
for i = 1:2:n 
    product = product * i; 
end 
fprintf('The product of all the odd numbers from 1 to %d is %d\n', n, product) 
+0

你可以使用没有循环的'prod(1:2:n)'。而且matlab对于任意的精度计算不是很好。 – Cheery 2014-11-06 04:04:19

+0

那会摆脱inf并给我一个真正的整数? – 2014-11-06 04:06:59

+0

不... ...'n'太大了! – rayryeng 2014-11-06 04:07:25

回答

0

您可以计算该数字,但不能原生。您需要使用MATLAB的可变精度算术方法或vpa。首先,以2为步长从1到1000创建矢量,然后将其封装为vpa对象。之后,按照Cheery的建议,并在此序列上拨打prod。因此,尝试这样的事情:

>> A = vpa(1:2:1000); 
>> prod(A) 

ans = 

1.007483297637508540040389173923e1283 

因此,这是在告诉我们,号码是1.00748 ......×10 ...哇!

+0

@KyleRogers - 我的荣幸! – rayryeng 2014-11-06 04:19:07

相关问题