Hello,

On Mon, Sep 28, 2009 at 2:32 PM, Nathann Cohen <nathann.co...@gmail.com> wrote:
> Hello !!!
>
> I used Sage to compute a few things today, which included at some step the
> mean of a list of values :
>
> def mean(l):
>     return sum(l)/len(l)
>
> At some point I was amazed by the fact I only had integer values, which was
> far from probable... The mean command had been defined in a script, then
> loaded through execfile or load. When I use mean(some_list) in Sage's
> console ( manually, by typing "mean.." ), I get the correct value. When a
> function defined in the same script file uses the "mean" method, it only
> gets integer values ( which seem to be the correct average, rounded in some
> way.... ). Is it normal/avoidable/worrying ? :-)

I think the difference is coming from what you pass in as the list.
For Python integers (like what you'd get with range(4)), their sum
will also be an 'int'.  Since len() always returns an 'int', Python
will use its integer floor division.  However, if you pass in floats
or Sage's Integer type, then that's what they'll sum to, and you'll
get what you expect.

>From the command-line, numbers are preparsed so that you don't get 'ints'.

sage: a = [1,2,4]
sage: map(type, a)

[<type 'sage.rings.integer.Integer'>,
 <type 'sage.rings.integer.Integer'>,
 <type 'sage.rings.integer.Integer'>]
sage: sum(a)/len(a)
7/3
sage: a = [int(1), int(2), int(4)]
sage: sum(a)
7
sage: sum(a)/len(a)
2

--Mike

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support-unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to