Looping Factorial that adds successive terms

1 回表示 (過去 30 日間)
David Ramirez
David Ramirez 2019 年 12 月 10 日
回答済み: Rik 2019 年 12 月 10 日
Writing a code that add sucessive terms but the denominator increases in increments of 1!.
So in example
p(x) = yi +ma(1) + a(2) m(m-1)/2!
I am unable to write a for loop that adds sucessive terms. Here is what I have
for m_2=2:n
mprod = mprod*((m+(1-(m_2-1)))/factorial(m_2-1));
yi = yi +a(m_2)*mprod;
end
My code i believe doesnt increase the factorials rather multiples them
  2 件のコメント
Rik
Rik 2019 年 12 月 10 日
It is not clear to me what your inputs are and how the calculations should be expanded. Can you give a few examples?
David Ramirez
David Ramirez 2019 年 12 月 10 日
I hope this helps this clears up what I was saying. The denominator just multiplies factorials rather than replacing it. I figured the rest out but I cannot get the denominator correct.
Code.PNG

サインインしてコメントする。

回答 (1 件)

Rik
Rik 2019 年 12 月 10 日
You should have just shown the last line. I first spent quite some time finding the correct method of implementing your non-desired output, instead of jumping immediately on the desired ouput.
%generate/pick some values
m=4;%this code also works for m=1, in which case it will return yi unchanged
a=rand(m+1,1);
yi=0;
%factors for the elements of a:
%m / 1
%m*(m-1) / 1*2
%m*(m-1)*(m-2)/ 1*2*3
numerator=m-( 0:(m-2) );
numerator=cumprod(numerator);
divisor=1:(m-1);
divisor=cumprod(divisor);
mprod=numerator./divisor;
mprod=reshape(mprod,[],1);%make the products the same shape as a(2:m)
%perform actual calculation
yi=yi + sum( a(2:m).*mprod );
The values in mprod seem extremely predictable. You should probably have a look at how to produce it directly, instead of dividing large numbers. At some point you will generate too large values and inaccuracies will creep in that you could avoid. I will leave that as an excersize for you.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by