所以我试图创建一个脚本来计算从1到1000的所有奇数的乘积(使用MATLAB)。程序运行但产品不正确: %程序用于计算从1到1000
的所有奇数的乘积% declare variable ‘product’ as zero
product = 0.;
% 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 :(得分:3)
目前,您的脚本设置为添加从1到1000的所有奇数。
要执行该产品,您只需将product
的起始值更改为1并在循环内相乘:
product = 1;
for i = 1:2:1000
product = product * i;
end
但是,创建一个向量并使内置prod
函数执行乘法更快:
product = prod(1:2:1000);
默认情况下,MATLAB在默认的64位数字中没有足够的内存来计算此产品的确切值。 这个数字太大了,因为这实际上是一个因子。
你会发现MATLAB为你正在乘以的500个数字返回Inf
,并且它最多只能包含150个元素。
事实上,使用浮点运算,使用浮点数的前17位数字为only accurate up to 15 digits(整数也在该级别饱和)。
使用Mathematica(由于我感觉懒惰,它可以开箱即用地执行任意数字算术),我可以看到答案需要至少1300位精度,我们可以让MATLAB通过符号来完成工具箱的vpa
功能:
digits(1300);
p = vpa(1);
pint = vpa(1);
for k = 2:N
pint = pint*p(k);
end
disp(pint);
>> StackOverflow
100748329763750854004038917392303538250323418583550415705013777513334847930864905026212149922688916514224446856302103818809813965739969905602683824057028542369814437703275217182106137628427025253936696857063927677887236450311036887007989218384076420973974651860279864376153012567675767840733574225799002463604490891982796305162134708837541147007332276627034016790073315219533088052639255340728943149219519187498959529434982654113006616219355830114439411562650611374970334868978510289340267833632215930432706056111069583472778227977585526504938921664232801595705593340414168289146933191250605578218896799783237156997993612173843567447982392426109444012350386990916069363415575527636429080027392875413821124412782341957015410685185402984322002697631153866494712956244870206835064084512590679022924697003630949759950902438767963278695296882620493296103779237046934780464541286585179975172680371269700518965123152181467825566303777704391998857792627009043170482928030252033752456172692668989206857862233381387134495504231267039972111966329704875185659372569246229419619030694680808504265784672316785572965414328005856656944666840982779185954031239345256896720409853053597049715408663604581472840976596002762935980048845023622727663267632821809277089697420848324327380396425724029541015625.0