Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.
|
|
|
Re: calculating euler products [newbie]
Posted:
Jan 5, 2012 3:21 PM
|
|
On 5 jan, 19:32, "John D'Errico" <woodch...@rochester.rr.com> wrote: > Jean Dupont <jeandupont...@gmail.com> wrote in message <9e730b1e-4327-4e8d-82b7-5201e21a2...@z17g2000vbe.googlegroups.com>... > > I've written the function below to calculate euler-products, I was > > wondering how it can be improved i.e. written more in "matlab-style" > > perhaps reducing execution time for large numbers > > > regards, > > Jean > > > function eulerprod(n) > > %calculate PI(1/(1-p^-1)) for all primes smaller than n > > prime=primes(n); > > nop=length(prime) > > factor=1 > > for i=1:nop > > factor=factor/(1-prime(i)^(-1)); > > y(i)=factor; > > end > > plot([1:nop],y) > > You need to start thinking in terms of vectors. Skip > the loops. > > First of all, this first is fine. Always use existing tools (like > primes) when you can. > > p = primes(n); > > But then why not process them all at once? Can you invert > every element of a vector, all at once? What does this do? > > 1./p > > Or this? > > 1 - 1./p > > Or this? > > 1./(1 - 1./p) > > Now, is there any function that can take the product of an > entire vector? Look for it. Of course, you actually want what > might be called the cumulative product. Is there such a thing > already defined in matlab as a function? > > Learn to use the lookfor function when you are not sure what > the name of a function might be. In this case I'll bet that > > lookfor product > > might yield something very useful. > > John
I think this is what you had in mind? function cumeulerprod(n) %calculate PI(1/(1-p^-1)) for all primes smaller than n p=primes(n); y=cumprod(1./(1-1./p)); plot(y)
regards, Jean
|
|
|
|