Looping Factorial that adds successive terms

1 Ansicht (letzte 30 Tage)
David Ramirez
David Ramirez am 10 Dez. 2019
Beantwortet: Rik am 10 Dez. 2019
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 Kommentare
Rik
Rik am 10 Dez. 2019
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 am 10 Dez. 2019
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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Rik
Rik am 10 Dez. 2019
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.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by