Friday 15 January 2010

matlab - Calculating the product of all the odd numbers -



matlab - Calculating the product of all the odd numbers -

so trying create script calculates product of odd numbers 1 1000 (using matlab). programme runs product not correct: %program meant calculate product of odd numbers 1 1000

% declare variable ‘product’ 0 product = 0.; % initialize counter, ‘n’, 1000 n = 1000; = 1:2:n product = product + i; end fprintf('the product of odd numbers 1 %d %d\n', n, product)

so i'm not sure how go , looking guidance. thanks!

solution

currently, script set add of odd numbers 1 1000. perform product, need alter starting value of product 1 , multiply within loop:

product = 1; = 1:2:1000 product = product * i; end

however, faster create vector , have built-in prod function perform multiplication:

product = prod(1:2:1000); problem

matlab not default have plenty memory in default 64-bit numbers compute exact value of product. number big since factorial.

you'll find matlab returns inf 500 numbers you're multiplying, , finite 150 elements. in fact, using floating point arithmetic, number only accurate 15 digits first 17 digits using floats (integers saturate @ level well).

using mathematica (which can perform arbitrary digit arithmetic out-of-the-box since i'm feeling lazy), can see reply needs @ to the lowest degree 1300 digits of precision, can have matlab through symbolic toolbox's vpa function:

digits(1300); p = vpa(1); pint = vpa(1); k = 2:n pint = pint*p(k); end disp(pint); >> stackoverflow 100748329763750854004038917392303538250323418583550415705013777513334847930864905026212149922688916514224446856302103818809813965739969905602683824057028542369814437703275217182106137628427025253936696857063927677887236450311036887007989218384076420973974651860279864376153012567675767840733574225799002463604490891982796305162134708837541147007332276627034016790073315219533088052639255340728943149219519187498959529434982654113006616219355830114439411562650611374970334868978510289340267833632215930432706056111069583472778227977585526504938921664232801595705593340414168289146933191250605578218896799783237156997993612173843567447982392426109444012350386990916069363415575527636429080027392875413821124412782341957015410685185402984322002697631153866494712956244870206835064084512590679022924697003630949759950902438767963278695296882620493296103779237046934780464541286585179975172680371269700518965123152181467825566303777704391998857792627009043170482928030252033752456172692668989206857862233381387134495504231267039972111966329704875185659372569246229419619030694680808504265784672316785572965414328005856656944666840982779185954031239345256896720409853053597049715408663604581472840976596002762935980048845023622727663267632821809277089697420848324327380396425724029541015625.0

matlab for-loop

No comments:

Post a Comment