Creating Catalan number loop and graphing it [python] - python

Let me preface it with that I am new to python completely and programming for that matter and I need to create a program to print all Catalan numbers up to one trillion. I have the basics of the program written out but I can't seem to understand why I'm not getting the right numbers. Also I am running into programs when trying to graph the trend out. Thanks in advance and here is the code I have:
import numpy as np
import scipy as sp
from pylab import *
def Catalan(n):
if n==0:
return (1)
elif n==1:
return (1)
else:
return ((4*n+2)/(n+2))*Catalan(n-1)
for n in range(18):
print (Catalan(n))
n=np.linspace(0,18,100)
y=Catalan(n)
plot(n,y,'r')
show()

There are two main mistakes in your Catalan function.
First, as seen in http://en.wikipedia.org/wiki/Catalan_number, the formula you wrote is useful to compute Catalan(n+1) in terms of Catalan(n). To use it to compute Catalan(n) in terms of Catalan(n-1), as you do, you must shift the index. So it should be (4*n-2)/(n+1)*Catalan(n-1).
Second, python uses integer arithmetic when dealing with ints. So, the quotients get rounded down to ints (this is, 5/2 gives 2, not 2.5). One way to deal with this is to write first the product and then the quotient: (4*n-2)*Catalan(n-1)/(n+1).

Nevermind programming, your formula looks broken. Take n=2:
return ((4*n+2)/(n+2))*Catalan(n-1)
= ((4*2+2)/(2+2))*Catalan(2-1)
= (( 8 +2)/( 4 ))*Catalan( 1 )
= (( 10 )/ 4 )* 1
= 2.5

Related

How can I randomly choose a number without using an 'If'?

Basically, I'm messing around in Python (3) and I'm trying to define some functions to do some common tasks in single lines, using as less memory as possible
For example, in video games, you might want a character to turn some degrees left/right, but not 0 degrees. So, given an integer x, how could you return a random integer between -x and +x` (inclusive) which isn't 0?
Note, I'm going for one-liners using minimum memory.
I'm posting an answer but I'd also like to know how other people would approach this.
EDIT: This isn' school homework or anything, I'm just designing a video game and defining a few functions which will come in handy. I said no 'If's because I was wondering if it was possible, and if so, how.
Thanks :-)
I would suggest:
import random
def randint_between(x):
return random.choice([-1, 1]) * random.randint(1, x)
I would use:
import random
def between(x):
return ((((random.randint(0, 1) * 2) - 1) * random.randint(1, x))
random.sample works with ranges which are very small compared to the range of numbers they provide.
This create a positive number between 1 and x and multiplies it with 1 or -1.
import random
def between(x):
return random.sample(range(1, x+1),k=1)[0] * (-2*random.randint(0,1)+1)
After looking at kch answer, I would probably go his approach.

Lua: Decompose a number by powers of 2

This question is a parallel to python - How do I decompose a number into powers of 2?. Indeed, it is the same question, but rather than using Python (or Javascript, or C++, as these also seem to exist), I'm wondering how it can be done using Lua. I have a very basic understanding of Python, so I took the code first listed in the site above and attempted to translate it to Lua, with no success. Here's the original, and following, my translation:
Python
def myfunc(x):
powers = []
i = 1
while i <= x:
if i & x:
powers.append(i)
i <<= 1
return powers
Lua
function powerfind(n)
local powers = {}
i = 1
while i <= n do
if bit.band(i, n) then -- bitwise and check
table.insert(powers, i)
end
i = bit.shl(i, 1) -- bitwise shift to the left
end
return powers
end
Unfortunately, my version locks and "runs out of memory". This was after using the number 12 as a test. It's more than likely that my primitive knowledge of Python is failing me, and I'm not able to translate the code from Python to Lua correctly, so hopefully someone can offer a fresh set of eyes and help me fix it.
Thanks to the comments from user2357112, I've got it fixed, so I'm posting the answer in case anyone else comes across this issue:
function powerfind(n)
local powers = {}
i = 1
while i <= n do
if bit.band(i, n) ~= 0 then -- bitwise and check
table.insert(powers, i)
end
i = bit.shl(i, 1) -- bitwise shift to the left
end
return powers
end
I saw that in the other one, it became a sort of speed contest. This one should also be easy to understand.
i is the current power. It isn't used for calculations.
n is the current place in the array.
r is the remainder after a division of x by two.
If the remainder is 1 then you know that i is a power of two which is used in the binary representation of x.
local function powerfind(x)
local powers={
nil,nil,nil,nil,
nil,nil,nil,nil,
nil,nil,nil,nil,
nil,nil,nil,nil,
}
local i,n=1,0
while x~=0 do
local r=x%2
if r==1 then
x,n=x-1,n+1
powers[n]=i
end
x,i=x/2,2*i
end
end
Running a million iterations, x from 1 to 1000000, takes me 0.29 seconds. I initialize the size of the powers table to 16.

Writing a double sum in Python

I am new to StackOverflow, and I am extremely new to Python.
My problem is this... I am needing to write a double-sum, as follows:
The motivation is that this is the angular correction to the gravitational potential used for the geoid.
I am having difficulty writing the sums. And please, before you say "Go to such-and-such a resource," or get impatient with me, this is the first time I have ever done coding/programming/whatever this is.
Is this a good place to use a "for" loop?
I have data for the two indices (n,m) and for the coefficients c_{nm} and s_{nm} in a .txt file. Each of those items is a column. When I say usecols, do I number them 0 through 3, or 1 through 4?
(the equation above)
\begin{equation}
V(r, \phi, \lambda) = \sum_{n=2}^{360}\left(\frac{a}{r}\right)^{n}\sum_{m=0}^{n}\left[c_{nm}*\cos{(m\lambda)} + s_{nm}*\sin{(m\lambda)}\right]*\sqrt{\frac{(n-m)!}{(n+m)!}(2n + 1)(2 - \delta_{m0})}P_{nm}(\sin{\lambda})
\end{equation}
(2) Yes, a "for" loop is fine. As #jpmc26 notes, a generator expression is a good alternative to a "for" loop. IMO, you'll want to use numpy if efficiency is important to you.
(3) As #askewchan notes, "usecols" refers to an argument of genfromtxt; as specified in that documentation, column indexes start at 0, so you'll want to use 0 to 3.
A naive implementation might be okay since the larger factorial is the denominator, but I wouldn't be surprised if you run into numerical issues. Here's something to get you started. Note that you'll need to define P() and a. I don't understand how "0 through 3" relates to c and s since their indexes range much further. I'm going to assume that each (and delta) has its own file of values.
import math
import numpy
c = numpy.getfromtxt("the_c_file.txt")
s = numpy.getfromtxt("the_s_file.txt")
delta = numpy.getfromtxt("the_delta_file.txt")
def V(r, phi, lam):
ret = 0
for n in xrange(2, 361):
for m in xrange(0, n + 1):
inner = c[n,m]*math.cos(m*lam) + s[n,m]*math.sin(m*lam)
inner *= math.sqrt(math.factorial(n-m)/math.factorial(n+m)*(2*n+1)*(2-delta[m,0]))
inner *= P(n, m, math.sin(lam))
ret += math.pow(a/r, n) * inner
return ret
Make sure to write unittests to check the math. Note that "lambda" is a reserved word.

Python function to solve Ax = b by back substitution

Okay, for my numerical methods class I have the following question:
Write a Python function to solve Ax = b by back substitution, where A is an upper triangular nonsingular matrix. MATLAB code for this is on page 190 which you can use as a pseudocode guide if you wish. The function should take as input A and b and return x. Your function need not check that A is nonsingular. That is, assume that only nonsingular A will be passed to your function.
The MATLAB code that it refers to is:
x(n) = c(u)/U(n,n)
for i = n-1 : -1 : 1
x(i) = c(i);
for j = i+1 : n
x(i) = x(i) - U(i,j)*x(j);
end
x(i) = x(i)/U(i,i);
end
My Python code, which I wrote using the MATLAB code snippet, is with an upper triangular test matrix(not sure if its nonsingular! How do I test for singularity?):
from scipy import mat
c=[3,2,1]
U=([[6,5,1],[0,1,7],[0,0,2]])
a=0
x=[]
while a<3:
x.append(1)
a=a+1
n=3
i=n-1
x[n-1]=c[n-1]/U[n-1][n-1]
while i>1:
x[i]=c[i]
j=i+1
while j<n-1:
x[i]=x[i]-U[i][j]*x[j];
x[i]=x[i]/U[i][i]
i=i-1
print mat(x)
The answer I am getting is [[1 1 0]] for x. I not sure if I am doing this correctly. I assume it is wrong and can't figure out what to do next. Any clues?
j=i+1
while j<n-1:
x[i]=x[i]-U[i][j]*x[j];
is infinite ... and never gets executed
your indexing is fubared:
for i in range(n-2,-1,-1):
....
for j in range(i+1,n):
notice, range is half open unlike matlab
One problem I see is that your input consists of integers, which means that Python is going to do integer division on them, which will turn 3/4 into 0 when what you want is floating point division. You can tell python to do floating point division by default by adding
from __future__ import division
To the top of your code. From the use of scipy, I'm assuming you're using Python 2.x here.
You ask how to test for singularity of an upper triangular matrix?
Please don't compute the determinant!
Simply look at the diagonal elements. Which ones are zero? Are any zero?
How about effective numerical singularity? Compare the smallest absolute value to the largest in absolute value. If that ratio is smaller than something on the order of eps, it is effectively singular.

Calculate poisson probability percentage

When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:
an integer
an 'average' number
and returns a float.
In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).
for example:
print poisson(2.6,6)
returns [1 3 3 0 1 3] (and every time I run it, it's different).
The number I get from calc/excel is 3.19 (POISSON(6,2.16,0)*100).
Am I using the python's poisson wrong (no pun!) or am I missing something?
scipy has what you want
>>> scipy.stats.distributions
<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>
>>> scipy.stats.distributions.poisson.pmf(6, 2.6)
array(0.031867055625524499)
It's worth noting that it's pretty easy to calculate by hand, too.
It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:
def poisson_probability(actual, mean):
# naive: math.exp(-mean) * mean**actual / factorial(actual)
# iterative, to keep the components from getting too large or small:
p = math.exp(-mean)
for i in xrange(actual):
p *= mean
p /= i+1
return p
This page explains why you get an array, and the meaning of the numbers in it, at least.

Categories