Problem with extremely small real number

Duncan Smith buzzard at urubu.freeserve.co.uk
Mon Sep 3 11:39:48 EDT 2007


Andrea wrote:
> Hi,
> I need to calculate this probability P!/{n \choose p}, varying both n
> and p, n takes values in this range [512:1024] and p in [2:12].
> So i write this code in python:
> 
> def factorial(n):
> 	result=1
> 	if n==0: return 1
> 	for i in xrange(1, abs(n)+1):
> 		result = i*result
> 	if n >= 0:
> 		return result
> 	else:
> 		return -result
> def binomial(n, k):
> 	assert n>0 and isinstance(n, (int, long)) and isinstance(k,
> (int,long))
> 	if k < 0 or k > n:
> 		return 0
> 	if k == 0 or k == n:
> 		return 1
> 	return factorial(n) // (factorial(k) * factorial(n-k))
> 
> I want to call factorial(2)//binomial(1024,2) for example, in this way
> trivially I obtain 0 as probability, how can I obtain the probability
> forcing this division to output extremely small real numbers????
> 

'//' is floor division.

>>> 2/523776
0
>>> 2//523776
0
>>> float(2)/523776
3.8184261974584555e-006
>>> from __future__ import division
>>> 2/523776
3.8184261974584555e-006
>>> 2//523776
0
>>>

Duncan



More information about the Python-list mailing list