Hi Francois,

> I play with random in order to approximate Pi by Monte-Carlo method.
>
> sage: n=10^5 ; len(filter(lambda t:t, [random()^2+random^2() < 1 for k in 
> [1..n]])) / len([1..n])
>
> The test looks at the point (random(), random()) and tests if it's in the 
> quarter circle.
> The result may be about pi/4.
>
> I get 0. Indeed the result of len is an int, not a Integer.
>
> Must I retain that len(L) is a Python int ?
> What is the advantage to get a Python int from len(L) ? What are the others 
> cases ?

Unfortunately yes ! This is written in python specifications:

    object.__len__(self)

    Called to implement the built-in function len(). Should return the length
    of the object, an integer >= 0. Also, an object that doesn’t define a
    __nonzero__() method and whose __len__() method returns zero is considered
    to be false in a Boolean context.

> Is it a way to get an Integer without change of the syntax ?

Unfortunately not ! Here is what happens if you try

    sage: class bla(object):
    ....:     def __len__(self): return Integer(10)^100
    ....: 
    sage: toto = bla()
    sage: len(toto)
    ---------------------------------------------------------------------------
    OverflowError                             Traceback (most recent call last)
    [...]
    OverflowError: long int too large to convert to int

As a consequence in Sage, the number of element of a set S is computed by
S.cardinality() which can be any large Integer or even Infinity. 

> I dislike the Integer(len(....)), and in tex I code lenORI = len ; len = 
> Integer(lenORI))
> Is there a method for Sage.

Why not making a loop::

    success = 1
    for k in [1..n]:
        if random()^2 + random()^2 < 1:
            success + =1
    approx = success / n

Cheers,

Florent

-- 
To post to this group, send an email to [email protected]
To unsubscribe from this group, send an email to 
[email protected]
For more options, visit this group at http://groups.google.com/group/sage-devel
URL: http://www.sagemath.org

Reply via email to