[Tutor] The '45' bug in round()

2007-03-19 Thread Dick Moores
Yesterday I was shocked, SHOCKED, to discover that round() is 
occasionally rounding incorrectly. For example,

 >>> print round(0.19945,4)
0.1994

For rounding of random samples of numbers between 0 and 1 ending in 
'45', the error ratio is about 0.041. Here are a few more examples:

 >>> print round(0.145, 2)
0.14

 >>> print round(0.5045, 3)
0.504

 >>> print round(0.34145, 4)
0.3414

 >>> print round(0.5170845, 6)
0.517084

 >>> print round(0.083400685245, 11)
0.08340068524

It may not be correct to call this a bug, but this is what I'm going 
to use until round() is revised:

def round2(n, digits=0):
 s = str(n)
 if '.' in s and s[-2:] == '45':
 mantissa = s.split('.')[1]
 if len(mantissa) - digits == 1:
 s = s[:-2] + '5'
 return s
 else:
 return round(float(s), digits)
 else:
 return round(float(n), digits)

Comments, Tutors? Am I way out in left field with this?

Dick Moores







0.504
0.505



0.083400685245
0.08340068524
0.08340068525

0.34145
0.3415
0.3414

0.29692817045
0.2969281705
0.2969281704

0.74945
0.7495
0.7494

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter-Button class

2007-03-19 Thread Kent Johnson
ammar azif wrote:
> Hi,
> 
> Thanks for the help guys.
> 
> 
> I have tried gui programming using Tkinter and use the Button class 
> which accepts the command argument which is a function object.
> 
> The question is how to send arguments if the function accepts arguments.

A common way to do this is to use a lambda expression to bind the 
arguments, e.g.
Button(..., command = lambda: func_with_args(1, 2, 3))

For example see
http://www.daniweb.com/code/snippet610.html

You could also define explicit, short helper functions if you don't want 
to use lambdas.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The '45' bug in round()

2007-03-19 Thread Kent Johnson
Dick Moores wrote:
> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,
> 
>  >>> print round(0.19945,4)
> 0.1994
> 
> For rounding of random samples of numbers between 0 and 1 ending in 
> '45', the error ratio is about 0.041. Here are a few more examples:

As I said yesterday, these are numbers that don't have an exact 
representation as binary floating point numbers. The actual 
representation is slightly less than what you ask for and it is rounded 
correctly. The repr() function will show a decimal approximation of the 
actual binary number:

In [1]: repr(.19945)
Out[1]: '0.19944'

For example 0.19945 is actually stored as approximately 
0.19944. What should be the result of
round(0.19944, 4)

This is an inherent limitation of binary floating point, not a bug. If 
you want exact representation of decimal fractions use the decimal module.
Read more here:
http://docs.python.org/tut/node16.html

> Comments, Tutors? Am I way out in left field with this?

IMO yes.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The '45' bug in round()

2007-03-19 Thread andrew clarke
On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:

> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,

"Garbage In, Garbage Out" :-)

Floating point numbers in Python (and other computer languages) are only
an approximation:

>>> print round(0.145, 2)
0.14
>>> 0.145
0.14499
>>> print round(0.145001, 2)
0.15

http://docs.python.org/tut/node16.html has some more information about
this.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The '45' bug in round()

2007-03-19 Thread Dick Moores
At 03:29 AM 3/19/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Yesterday I was shocked, SHOCKED, to discover that round() is 
>>occasionally rounding incorrectly. For example,
>>  >>> print round(0.19945,4)
>>0.1994
>>For rounding of random samples of numbers between 0 and 1 ending in 
>>'45', the error ratio is about 0.041. Here are a few more examples:
>
>As I said yesterday, these are numbers that don't have an exact 
>representation as binary floating point numbers. The actual 
>representation is slightly less than what you ask for and it is 
>rounded correctly. The repr() function will show a decimal 
>approximation of the actual binary number:
>
>In [1]: repr(.19945)
>Out[1]: '0.19944'
>
>For example 0.19945 is actually stored as approximately 
>0.19944. What should be the result of
>round(0.19944, 4)
>
>This is an inherent limitation of binary floating point, not a bug. 
>If you want exact representation of decimal fractions use the decimal module.
>Read more here:
>http://docs.python.org/tut/node16.html
>
>>Comments, Tutors? Am I way out in left field with this?
>
>IMO yes.

Kent, I did understand the points you made in that earlier thread. 
However, I'm unhappy with

 >>> print round(0.19945,4)
0.1994

Am I the only one unhappy with this kind of rounding?

My function, round2() restores me to happiness.  :)

 >>> print round2(0.19945,4)
0.1995

Is there something wrong with it?

Here it is again:

def round2(n, digits=0):
 s = str(n)
 if '.' in s and s[-2:] == '45':
 mantissa = s.split('.')[1]
 if len(mantissa) - digits == 1:
 s = s[:-2] + '5'
 return s
 else:
 return round(float(s), digits)
 else:
 return round(float(n), digits)

Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter-Button class

2007-03-19 Thread Kent Johnson
ammar azif wrote:
> Hi,
> 
> Thanks for answering .. btw what do you mean by explicit , helper 
> function? Can you explain about these functions?

I just mean, define an ordinary function of no arguments that does what 
you want. For example, the calculator program I linked to has this Button:
tk.Button(root,text='1',width=5,relief=tk.RIDGE,
   command=lambda: click('1'))

That could be written as
def click1():
   click('1')
tk.Button(root,text='1',width=5,relief=tk.RIDGE, command=click1)

Notice there are no parentheses after 'click1' in the Button definition; 
you are passing the actual function to the Button.

Kent

PS Please reply on-list.

> 
> */Kent Johnson <[EMAIL PROTECTED]>/* wrote:
> 
> ammar azif wrote:
>  > Hi,
>  >
>  > Thanks for the help guys.
>  >
>  >
>  > I have tried gui programming using Tkinter and use the Button class
>  > which accepts the command argument which is a function object.
>  >
>  > The question is how to send arguments if the function accepts
> arguments.
> 
> A common way to do this is to use a lambda expression to bind the
> arguments, e.g.
> Button(..., command = lambda: func_with_args(1, 2, 3))
> 
> For example see
> http://www.daniweb.com/code/snippet610.html
> 
> You could also define explicit, short helper functions if you don't
> want
> to use lambdas.
> 
> Kent
> 
> 
> 
> Don't pick lemons.
> See all the new 2007 cars 
> 
>  
> at Yahoo! Autos. 
> 
>  
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The '45' bug in round()

2007-03-19 Thread Kent Johnson
Dick Moores wrote:

> Kent, I did understand the points you made in that earlier thread. 
> However, I'm unhappy with
> 
>  >>> print round(0.19945,4)
> 0.1994
> 
> Am I the only one unhappy with this kind of rounding?

IMO you are chasing a non-problem. In real-world use, you would probably 
not type in a number and then immediately round it. You would round the 
result of some calculation that itself starts with inexact values and 
then introduces more error. To take the result of this calculation and 
second-guess it seems silly to me.

> My function, round2() restores me to happiness.  :)

Well I should leave well enough alone then :-)

>  >>> print round2(0.19945,4)
> 0.1995
> 
> Is there something wrong with it?

If you want exact decimal representations you may be better off using 
the decimal module than trying to patch binary floating point. Though 
decimal has its own representation error...

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Making table

2007-03-19 Thread Per Jr. Greisen

Hi,
I need to generate a table with different x,y,z values and write them to a
file:
10.171  -15.243 -2.558
9.837   -14.511 -1.923
-23.451 -13.870 51.507

I would like to write to the files as columns
10.171   -15.243   -2.558
  9.837   -14.511   -1.923
-23.451   -13.870  51.507
  0.233  0.4530.111

so the number are correctly aligned. Does anybody know a function that can
align the numbers.
Any advice or help appreciated. Thanks in advance.
--
Best regards
Per
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-19 Thread Dave Kuhlman
On Mon, Mar 19, 2007 at 01:11:27PM +0100, Per Jr. Greisen wrote:
> Hi,
> I need to generate a table with different x,y,z values and write them to a
> file:
> 10.171  -15.243 -2.558
> 9.837   -14.511 -1.923
> -23.451 -13.870 51.507
> 
> I would like to write to the files as columns
> 10.171   -15.243   -2.558
>   9.837   -14.511   -1.923
> -23.451   -13.870  51.507
>   0.233  0.4530.111
> 
> so the number are correctly aligned. Does anybody know a function that can
> align the numbers.
> Any advice or help appreciated. Thanks in advance.

Try ljust and rjust.  They are string functions/methods and are
described here: http://docs.python.org/lib/string-methods.html

Something like the following might work for you:

In [1]: value = 3.45678
In [2]: ("%0.3f" % value).rjust(10)
Out[2]: ' 3.457'

(using the ipython interactive shell)

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cookie expiration date format

2007-03-19 Thread Mike Hansen
 

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of Luke Paireepinart
> Sent: Friday, March 16, 2007 8:31 PM
> To: Tim Johnson
> Cc: tutor@python.org
> Subject: Re: [Tutor] cookie expiration date format
> 
> Tim Johnson wrote:
> > Hi:
> > I want to be able to expire a cookie programmatically.
> > In other languages, I just set the expiration date to 'yesterday'.
> > If I look at the documentation at:
> > http://docs.python.org/lib/node644.html
> > for the Cookie object, I see the following:
> > ---
> > expires
> > Integer expiry date in seconds since epoch,
> > ---
> > I'm not clear what datatype is needed here.
> > Can anyone clarify this for me?
> >   
> Sounds like it's an integer or float, such as returned by time.time()
>  >>> import time
>  >>> time.time()
> 1174098190.796 #seconds since epoch
>  >>> _ / 60
> 19568303.17992#minutes since epoch
>  >>> _ / 60
> 326138.386332 #hours ..
>  >>> _ / 24
> 13589.099430509259# days
>  >>> _ / 365.25
> 37.204926572236161 #years
>  >>> .205 * 1.2
> 0.24597  #months ( fractional part of year )
>  >>>
> 
> So today is 37 years 2.5 months from January 1, 1970.
> 1970 + 37 = 2007, and January 1 + 2.5 months = March 16.
> 
> If you wanted the cookie to expire 24 hours from now,
> time.time() + 3600 * 24 #(seconds in a day)
> 
> See http://en.wikipedia.org/wiki/Unix_epoch for more info on 
> the epoch.
> look into the time and the datetime modules, there should be 
> an easy way 
> to find the seconds since epoch for whatever date you want.
> HTH,
> -Luke

Some of the modules in the Python standard library make things a little
more difficult than other languages.(Perl, Ruby, ...) This is a good
example of it. Are there any 3rd party modules that let you set the
expiration date to 'yesterday'? I know I could write a wrapper, but I'd
rather not re-invent the wheel and save some time.

Another example is ftplib. Other language's ftp modules/libraries allow
you do something like sendaciifile(fh) or sendbinaryfile(fh) yet you
need to build your own wrapper functions in Python.
http://effbot.org/librarybook/ftplib.htm 

Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-19 Thread Kent Johnson
Dave Kuhlman wrote:
> Try ljust and rjust.  They are string functions/methods and are
> described here: http://docs.python.org/lib/string-methods.html
> 
> Something like the following might work for you:
> 
> In [1]: value = 3.45678
> In [2]: ("%0.3f" % value).rjust(10)
> Out[2]: ' 3.457'

Most string formatting conversions allow you to specify a width 
directly. For example,
In [61]: value = 3.45678
In [63]: "%10.3f" % value
Out[63]: ' 3.457'

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-19 Thread Switanek, Nick
Thanks very much for your help.

I did indeed neglect to put the "print" in the code that I sent to the
list.

It appears that the step that is taking a long time, and that therefore
makes me think that the script is somehow broken, is creating a
dictionary of frequencies from the list of ngrams. To do this, I've
written, for example:

bigramDict = {}
bigrams = [' '.join(wordlist[i:i+2]) for i in range(len(wordlist)-2+1)]
for bigram in bigrams:
if bigram in bigramDict.keys(): bigramDict[bigram] += 1
else: bigramDict[bigram] = 1


With around 500,000 bigrams, this is taking over 25 minutes to run (and
I haven't sat around to let it finish) on an XP machine at 3.0GHz and
1.5GB RAM. I bet I'm trying to reinvent the wheel here, and that there
are faster algorithms available in some package. I think possibly an
indexing package like PyLucene would help create frequency dictionaries,
but I can't figure it out from the online material available. Any
suggestions?

Thanks,
Nick



-Original Message-
From: Jerry Hill [mailto:[EMAIL PROTECTED] 
Sent: Friday, March 16, 2007 12:52 PM
To: Switanek, Nick
Cc: tutor@python.org
Subject: Re: [Tutor] fine in interpreter, hangs in batch

On 3/16/07, Switanek, Nick <[EMAIL PROTECTED]> wrote:
> After creating a list of words ('wordlist'), I can run the following
> code in the interactive window of PythonWin in about ten seconds. If I
> run the script containing the code, the script seems to hang on the
> loop. I'd be grateful for help as to why; I often seem to have
something
> that works in the interpreter, but not when I run the script.

I'm not sure what you mean by 'seems to hang'.  The code that you
posted isn't complete enough to run (since you didn't provide a
definition of wordlist), and just generates a NameError exception.

Beyond that, I don't understand what the code is supposed to produce
for output.  As written, you generate a list in your loop and assign
it to the name ngrams, but never do anything with that list.  Since
you're inside a for loop, your ngrams name is overwritten the next
time you run through the loop.  You also generate a string with the
statement "Finished the %d-gram list." % n, but you don't do anything
with it.  You probably want to either print it, or assign it to a
variable to print later.

Something like this:

wordlist = ['apple', 'orange', 'pear', 'banana', 'coconut']
N = [2,3,4,5]
ngramlist = [wordlist]
for n in N:
   ngrams = [' '.join(wordlist[i:i+n]) for i in
range(len(wordlist)-n+1)]
   print "Finished the %d-gram list." % n
   print ngrams

produces the following output when run as a script:

Finished the 2-gram list.
['apple orange', 'orange pear', 'pear banana', 'banana coconut']
Finished the 3-gram list.
['apple orange pear', 'orange pear banana', 'pear banana coconut']
Finished the 4-gram list.
['apple orange pear banana', 'orange pear banana coconut']
Finished the 5-gram list.
['apple orange pear banana coconut']

Does that help?

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cookie expiration date format

2007-03-19 Thread Tim Johnson
On Monday 19 March 2007 15:33, Mike Hansen wrote:
 
 
> Some of the modules in the Python standard library make things a little
> more difficult than other languages.(Perl, Ruby, ...) This is a good
> example of it. Are there any 3rd party modules that let you set the
> expiration date to 'yesterday'? I know I could write a wrapper, but I'd
> rather not re-invent the wheel and save some time.

 I've written my own. The time format function was all I needed to handle
the expiration. Having had to write cookie objects in other languages from
scratch, I knew what I was after, just a matter of finding the right python
module and function to do it. datetime was the key.

> Another example is ftplib. Other language's ftp modules/libraries allow
> you do something like sendaciifile(fh) or sendbinaryfile(fh) yet you
> need to build your own wrapper functions in Python.
> http://effbot.org/librarybook/ftplib.htm

 Wrote my own wrapper for ftplib years ago. with those function included...

 I think it is inevitable that wrappers get written because programmers have
 unique circumstance and needs. In my case, I not only needed to expire a
 cookie, it served my needs to embedded multiple names and values in
 the cookie value.

 another example, I wrote a cgi wrapper so I could make calls like
 cgi["first_name"] ## where __getitem__ gets the value for posted field name

 I think the cookie library is great. Just needs some more docs and examples.
 (IMHO)
 that would make it easier for other programmers to write their own wrappers.

The function looks like this:
def expire(self,name):
c = self.get(name) ## retrieve cookie by name
if c: 
time_format = "%a, %d %b %Y"
expires = "%s" % (
(datetime.datetime.now() ## set the expiration 
date to yesterday
+ datetime.timedelta(-1)).strftime(time_format)
)   ## one second might be good enough!
self.expires = expires
self.set(name,c)
I choose not to override del (using __del__) because it would have 
necessitated a second argument to del(), as in del(cookie,cookie_name)
My class handless multiple cookies.

Thanks Mike
tim

> Mike
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <[EMAIL PROTECTED]>
Palmer, Alaska, USA
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-19 Thread Kent Johnson
Switanek, Nick wrote:
> Thanks very much for your help.
> 
> I did indeed neglect to put the "print" in the code that I sent to the
> list.
> 
> It appears that the step that is taking a long time, and that therefore
> makes me think that the script is somehow broken, is creating a
> dictionary of frequencies from the list of ngrams. To do this, I've
> written, for example:
> 
> bigramDict = {}
> bigrams = [' '.join(wordlist[i:i+2]) for i in range(len(wordlist)-2+1)]
> for bigram in bigrams:
>   if bigram in bigramDict.keys(): bigramDict[bigram] += 1
>   else: bigramDict[bigram] = 1

Ouch! bigramDict.keys() creates a *new* *list* of all the keys in 
bigramDict. You then search the list - a linear search! - for bigram. 
I'm not surprised that this gets slow.

If you change that line to
   if bigram in bigramDict: bigramDict[bigram] += 1
you should see a dramatic improvement.

Kent

> 
> 
> With around 500,000 bigrams, this is taking over 25 minutes to run (and
> I haven't sat around to let it finish) on an XP machine at 3.0GHz and
> 1.5GB RAM. I bet I'm trying to reinvent the wheel here, and that there
> are faster algorithms available in some package. I think possibly an
> indexing package like PyLucene would help create frequency dictionaries,
> but I can't figure it out from the online material available. Any
> suggestions?
> 
> Thanks,
> Nick

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-19 Thread Kent Johnson
Switanek, Nick wrote:
> Great, Kent, thanks. I thought that I had to check in the .keys() to see
> if the key was there. 
> 
> It seems that the method you suggest will not work if I'm looking for a
> value in the dictionary. If that's correct, is there a fast alternative
> to searching through .values()

Not directly. If you only need to search by values (not keys) consider 
if you can reverse the keys and values. (This probably won't work if you 
can have many keys with the same value.)

Alternately, maintain a set of values in parallel with the dictionary. 
If there are a lot of places where you need to do this, maybe you want 
to make a dict subclass that manages a helper set. A good place to start 
might be this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823

It doesn't do what you want but it is similar and shows which dict 
methods must be overridden.

Hmm, deleting entries could be tricky, you don't know whether to delete 
from the helper. Maybe keep a dict that maps values to a count of how 
many times the value appears in the main dict.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The '45' bug in round()

2007-03-19 Thread Michael Hannon
On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,
> 
>  >>> print round(0.19945,4)
> 0.1994
.
.
.
> Comments, Tutors? Am I way out in left field with this?


I suggest you might want to look at the discussion of unbiased rounding at:

http://en.wikipedia.org/wiki/Rounding

- Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-19 Thread Carroll, Barry
> -Original Message-
> Date: Mon, 19 Mar 2007 11:53:06 -0400
> From: Kent Johnson <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Making table
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Dave Kuhlman wrote:
> > Try ljust and rjust.  They are string functions/methods and are
> > described here: http://docs.python.org/lib/string-methods.html
> >
> > Something like the following might work for you:
> >
> > In [1]: value = 3.45678
> > In [2]: ("%0.3f" % value).rjust(10)
> > Out[2]: ' 3.457'
> 
> Most string formatting conversions allow you to specify a width
> directly. For example,
> In [61]: value = 3.45678
> In [63]: "%10.3f" % value
> Out[63]: ' 3.457'
> 
> Kent
> 
What if one wished to align the values in each column at the decimal
point?  Is there a simple means to do this in Python, or would one need
to write a new function?

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fine in interpreter, hangs in batch

2007-03-19 Thread Jerry Hill
On 3/19/07, Switanek, Nick <[EMAIL PROTECTED]> wrote:
> Thanks very much for your help.
>
> It appears that the step that is taking a long time, and that therefore
> makes me think that the script is somehow broken, is creating a
> dictionary of frequencies from the list of ngrams. To do this, I've
> written, for example:

Well, if you're guessing which part of your code is slow, you should
profile your code so you can stop guessing.  Python has some very
useful built in profiling tools, documented here:
http://docs.python.org/lib/profile.html

Take a look at the "Instant User's Manual", which should be enough to
get you started. Once you can see exactly which parts of your code are
taking the longest, then you'll know what the best targets are for
optimization.

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-19 Thread Kent Johnson
Carroll, Barry wrote:
>> -Original Message-
>> Date: Mon, 19 Mar 2007 11:53:06 -0400
>> From: Kent Johnson <[EMAIL PROTECTED]>

>> Most string formatting conversions allow you to specify a width
>> directly. For example,
>> In [61]: value = 3.45678
>> In [63]: "%10.3f" % value
>> Out[63]: ' 3.457'
>>
>> Kent
>>
> What if one wished to align the values in each column at the decimal
> point?  Is there a simple means to do this in Python, or would one need
> to write a new function?

If you specify the number of digits after the decimal point, that number 
of digits will always be given, so columns will line up:
In [86]: '%10.3f' % 1.2
Out[86]: ' 1.200'
In [87]: '%10.3f' % 1.23456
Out[87]: ' 1.235'

If you want something fancier I think you will have to do it yourself.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-19 Thread Carroll, Barry
> -Original Message-
> From: Kent Johnson [mailto:[EMAIL PROTECTED]
> Sent: Monday, March 19, 2007 12:59 PM
> To: Carroll, Barry
> Cc: tutor@python.org
> Subject: Re: [Tutor] Making table
> 
> Carroll, Barry wrote:
> >> -Original Message-
> >> Date: Mon, 19 Mar 2007 11:53:06 -0400
> >> From: Kent Johnson <[EMAIL PROTECTED]>
> 
> >> Most string formatting conversions allow you to specify a width
> >> directly. For example,
> >> In [61]: value = 3.45678
> >> In [63]: "%10.3f" % value
> >> Out[63]: ' 3.457'
> >>
> >> Kent
> >>
> > What if one wished to align the values in each column at the decimal
> > point?  Is there a simple means to do this in Python, or would one
need
> > to write a new function?
> 
> If you specify the number of digits after the decimal point, that
number
> of digits will always be given, so columns will line up:
> In [86]: '%10.3f' % 1.2
> Out[86]: ' 1.200'
> In [87]: '%10.3f' % 1.23456
> Out[87]: ' 1.235'
> 
> If you want something fancier I think you will have to do it yourself.
> 
> Kent
Kent:

Thanks for your response.  That method is certainly good enough for
general use.  What about a case where the user needs to keep track of
significant digits? As an example, assume that the following values
(pulled arbitrarily from my head, I admit) are accurate to three
significant digits:

253.
77.6
9.03
.0210

Using a formatting string of "%10.4f", these would be rendered as:

'  253.'
'   77.6000
'9.0300'
'0.0210'

This formatting gives the impression that all values but the last are
more precise than they truly are.  A scientist or statistician would
prefer to see something like this:

'254.'
' 77.6   '
'  9.03  '
'  0.0210'

Does numpy or some other math package have that capability?

Thanks again.
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor