[Tutor] run with default value if input not given
Hi, #!/usr/bin/env python import sys x = 'Saad is a boy' def main(x): a = [] b = x.split(' ') for item in b: a.append(item) print a if __name__ == '__main__': x = sys.argv[1] main(x) How can I make this program run with the default value of x if I don't specify an argument at the command line? It should do this: saad@saad:~$ python test.py Mariam is a girl ['Mariam', 'is', 'a', 'girl'] saad@saad:~$ python test.py ['Saad', 'is', 'a', 'boy'] But the simply running test.py gives: Traceback (most recent call last): File input_test.py, line 13, in module x = sys.argv[1] IndexError: list index out of range Saad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
I've come up with this: try: sys.argv[1] x = sys.argv[1] main(x) except IndexError: main(x) It works but seems hackish. Saad On Monday, October 29, 2012, Saad Javed wrote: Hi, #!/usr/bin/env python import sys x = 'Saad is a boy' def main(x): a = [] b = x.split(' ') for item in b: a.append(item) print a if __name__ == '__main__': x = sys.argv[1] main(x) How can I make this program run with the default value of x if I don't specify an argument at the command line? It should do this: saad@saad:~$ python test.py Mariam is a girl ['Mariam', 'is', 'a', 'girl'] saad@saad:~$ python test.py ['Saad', 'is', 'a', 'boy'] But the simply running test.py gives: Traceback (most recent call last): File input_test.py, line 13, in module x = sys.argv[1] IndexError: list index out of range Saad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
Saad, please don't send HTML emails, as it destroys the essential formatting of your code. On Mon, Oct 29, 2012 at 11:06:14AM +0500, Saad Javed wrote: How can I make this program run with the default value of x if I don't specify an argument at the command line? arguments = sys.argv[1:] # get the list of command line arguments if arguments: # There are some. process(arguments) else: # There are no arguments. do_something_else() Or if you prefer, check that len(sys.argv) 1. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
On Mon, Oct 29, 2012 at 11:28:05AM +0500, Saad Javed wrote: I've come up with this: try: sys.argv[1] x = sys.argv[1] main(x) except IndexError: main(x) It works but seems hackish. There's no need to look up sys.argv[1] twice, nor any need to write main(x) in both blocks. You can do each once only: try: # Always use the minimum code needed inside a try block. x = sys.argv[1] except IndexError: x = some default value main(x) Here's yet another way: args = sys.argv + [some default value] main(args[1]) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
Saad Javed wrote: Hi, #!/usr/bin/env python import sys x = 'Saad is a boy' def main(x): a = [] b = x.split(' ') for item in b: a.append(item) print a if __name__ == '__main__': x = sys.argv[1] main(x) How can I make this program run with the default value of x if I don't specify an argument at the command line? It should do this: saad@saad:~$ python test.py Mariam is a girl ['Mariam', 'is', 'a', 'girl'] saad@saad:~$ python test.py ['Saad', 'is', 'a', 'boy'] But the simply running test.py gives: Traceback (most recent call last): File input_test.py, line 13, in module x = sys.argv[1] IndexError: list index out of range Saad The argparse module (see http://docs.python.org/2/library/argparse.html) offers a flexible way to specify command line arguments. Your program would look like this: $ cat optional_arg.py #!/usr/bin/env python import argparse def main(): parser = argparse.ArgumentParser( description=Print a sentence as a list of words) parser.add_argument( sentence, nargs=?, default=Mary had a little lamb) args = parser.parse_args() words = args.sentence.split() print words if __name__ == __main__: main() ...and work like this: $ ./optional_arg.py ['Mary', 'had', 'a', 'little', 'lamb'] $ ./optional_arg.py That's all folks [That's, 'all', 'folks'] It would include help... $ ./optional_arg.py -h usage: optional_arg.py [-h] [sentence] Print a sentence as a list of words positional arguments: sentence optional arguments: -h, --help show this help message and exit ...and basic error reporting: $ ./optional_arg.py That\'s all folks usage: optional_arg.py [-h] [sentence] optional_arg.py: error: unrecognized arguments: all folks almost for free. So even if you find argparse too complex right now keep in mind that it exists until you are comfortable enough with Python to start making use of more parts of its standard library. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with homework
[SNIPPED] Always use a while loop in this situation, This is excellent advice. Use a for loop in two situations: 1. Iterating a fixed(known) number of times 2. Iterating through the contents of any container Use a while loop to iterate as long as a condition applies. regardless of whether or not teachers put stupid artificial constraints on your code, such as banning the use of len(). There may be legitimate learning outcomes for a teacher to specify such conditions. In this case, learning to use a counter that is incremented under certain conditions. I would hesitate to condemn in such strong terms without knowing more background. Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with homework
On 29/10/12 08:37, Asokan Pichai wrote: teachers put stupid artificial constraints on your code, such as banning the use of len(). There may be legitimate learning outcomes for a teacher to specify such conditions. In that case they should think up a scenario that requires the use of the construct that is most appropriate. Teachers should never encourage bad practice(*) and that's what this example does. It's valid to put constraints such as do not use any external modules or to use a specific construct if that's what's being taught. But it's never right to leave the student the freedom to use any solution *except* the one that is most logical and readily available. In this case, learning to use a counter that is incremented under certain conditions. But there are many better cases where that solution is needed rather than using len(). This one just sounds like lazy teaching. (*) Actually enforcing bad practice one to demonstrate the problems can be valid provided its followed immediately by the best practice alternative. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with homework
On Mon, Oct 29, 2012 at 2:28 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 29/10/12 08:37, Asokan Pichai wrote: teachers put stupid artificial constraints on your code, such as banning the use of len(). There may be legitimate learning outcomes for a teacher to specify such conditions. In that case they should think up a scenario that requires the use of the construct that is most appropriate. Teachers should never encourage bad practice(*) and that's what this example does. It's valid to put constraints such as do not use any external modules or to use a specific construct if that's what's being taught. But it's never right to leave the student the freedom to use any solution *except* the one that is most logical and readily available. In this case, learning to use a counter that is incremented under certain conditions. But there are many better cases where that solution is needed rather than using len(). This one just sounds like lazy teaching. (*) Actually enforcing bad practice one to demonstrate the problems can be valid provided its followed immediately by the best practice alternative. As a trainer, I believe using a bad example is WRONG; even to teach how not to write. Better to critique the suggested bad answers and explain why that is bad, rather than enforce a constraint that leads to a bad way and then call it out as bad explain why. That said, it *is* preferable IMO, not use such strong condemnation without knowing full background. Probably by now this is OT, so I should stop now. Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] greater precision?
Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; from math import pi, asin, atan2, cos, sin, sqrt from math import pi, asin, atan2, cos, sin, sqrt from crosspoint import crosspoint which are from the 1st and 2nd scripts, that are run to generate, then manipulate, the numbers (actually, polygon descriptions!). However, the 2nd script 'calls' a script called crosspoint.py, trimmed of most comments this is; # Python code to find the crossing point of two lines. # This function is optimised for big-integer or FP arithmetic: it # multiplies up to find two big numbers, and then divides them. def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2): Give the intersection point of the (possibly extrapolated) lines\n\ segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2). dxa = xa2-xa1 dya = ya2-ya1 dxb = xb2-xb1 dyb = yb2-yb1 if dya * dxb == dxa * dyb: return None if dxa == 0: return (xa1, (xa1 - xb1) * dyb / dxb + yb1) if dxb == 0: return (xb1, (xb1 - xa1) * dya / dxa + ya1) if dya == 0: return ((ya1 - yb1) * dxb / dyb + xb1, ya1) if dyb == 0: return ((yb1 - ya1) * dxa / dya + xa1, yb1) det = dya * dxb - dyb * dxa xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1 ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1 return (xtop / det, ytop / det) I am not sure what == means, nor if any 'special' maths functions are called from crosspoint.py (to me, it appears not?), so, as I understand it, the from math import line *is* the 'math engine' if you will, and is the source of the 12 sig fig limit, yes? One other odd thing that occurs, is when the scripts are run, a weird, small, non ASCII file called crosspoint.pyc is created? Is this the interpreter 'compiling' crosspoint.py ( either before, during, or after?) the 2nd script calls it? Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30 or more would be better!) I'd be a happy camper! XNumbers addon for Excel allows over 200 sig figs by switching to base 256 IIRC. It is this with which I'd like to examine the output of these pyto scripts at finer resolution, if that can be done in python??? Best Regards, John Collins. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] greater precision?
Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; from math import pi, asin, atan2, cos, sin, sqrt from math import pi, asin, atan2, cos, sin, sqrt from crosspoint import crosspoint which are from the 1st and 2nd scripts, that are run to generate, then manipulate, the numbers (actually, polygon descriptions!). However, the 2nd script 'calls' a script called crosspoint.py, trimmed of most comments this is; # Python code to find the crossing point of two lines. # This function is optimised for big-integer or FP arithmetic: it # multiplies up to find two big numbers, and then divides them. def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2): Give the intersection point of the (possibly extrapolated) lines\n\ segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2). dxa = xa2-xa1 dya = ya2-ya1 dxb = xb2-xb1 dyb = yb2-yb1 if dya * dxb == dxa * dyb: return None if dxa == 0: return (xa1, (xa1 - xb1) * dyb / dxb + yb1) if dxb == 0: return (xb1, (xb1 - xa1) * dya / dxa + ya1) if dya == 0: return ((ya1 - yb1) * dxb / dyb + xb1, ya1) if dyb == 0: return ((yb1 - ya1) * dxa / dya + xa1, yb1) det = dya * dxb - dyb * dxa xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1 ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1 return (xtop / det, ytop / det) I am not sure what == means, nor if any 'special' maths functions are called from crosspoint.py (to me, it appears not?), so, as I understand it, the from math import line *is* the 'math engine' if you will, and is the source of the 12 sig fig limit, yes? One other odd thing that occurs, is when the scripts are run, a weird, small, non ASCII file called crosspoint.pyc is created? Is this the interpreter 'compiling' crosspoint.py ( either before, during, or after?) the 2nd script calls it? Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30 or more would be better!) I'd be a happy camper! XNumbers addon for Excel allows over 200 sig figs by switching to base 256 IIRC. It is this with which I'd like to examine the output of these pyto scripts at finer resolution, if that can be done in python??? Best Regards, John Collins. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 10/29/2012 05:49 AM, John Collins wrote: Did you really leave two very-similar messages 3 minutes apart? Or are you using a broken gateway, like Google-groups, and it hiccoughed? Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; from math import pi, asin, atan2, cos, sin, sqrt from math import pi, asin, atan2, cos, sin, sqrt from crosspoint import crosspoint which are from the 1st and 2nd scripts, that are run to generate, then manipulate, the numbers (actually, polygon descriptions!). However, the 2nd script 'calls' a script called crosspoint.py, trimmed of most comments this is; # Python code to find the crossing point of two lines. # This function is optimised for big-integer or FP arithmetic: it # multiplies up to find two big numbers, and then divides them. def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2): Give the intersection point of the (possibly extrapolated) lines\n\ segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2). dxa = xa2-xa1 dya = ya2-ya1 dxb = xb2-xb1 dyb = yb2-yb1 if dya * dxb == dxa * dyb: return None if dxa == 0: return (xa1, (xa1 - xb1) * dyb / dxb + yb1) if dxb == 0: return (xb1, (xb1 - xa1) * dya / dxa + ya1) if dya == 0: return ((ya1 - yb1) * dxb / dyb + xb1, ya1) if dyb == 0: return ((yb1 - ya1) * dxa / dya + xa1, yb1) det = dya * dxb - dyb * dxa xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1 ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1 return (xtop / det, ytop / det) I am not sure what == means, nor if any 'special' maths functions are called from crosspoint.py (to me, it appears not?), so, as I understand it, the Without knowing the type of the arguments being passed to the crosspoint() function, we cannot say. I can GUESS that they are int, long, or float. But you can find that out by examining the source that's calling it. Judging from the comments, I might guess they're int or long, and if so, only the division being done in the function produces floats. If that's the case, then you're limited to float's precision. if they are some other type (eg. Decimal), then indeed there might be special functions being called. from math import line *is* the 'math engine' if you will, and is the source of the 12 sig fig limit, yes? That import gets you access to the particular symbols it imports. Normal arithmetic on floats is already built in, and doesn't need an import. I'm assuming you're using CPython, and you say it's on XP. So presumably you're running an Intel (or Intel-compatible) processor with binary floating point built-in. That processor is the limit of float values in normal use. It's good to about 18 digits. One other odd thing that occurs, is when the scripts are run, a weird, small, non ASCII file called crosspoint.pyc is created? Is this the interpreter 'compiling' crosspoint.py ( either before, during, or after?) the 2nd script calls it? Exactly. It's a side-effect of the first import of the module. On subsequent imports, the pyc file is used, unless the py file has been modified meanwhile. Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30 or more would be better!) I'd be a happy camper! XNumbers addon for Excel allows over 200 sig figs by switching to base 256 IIRC. It is this with which I'd like to examine the output of these pyto scripts at finer resolution, if that can be done in python??? Best Regards, John Collins. 18 digits is what you should get if the code is as I describe. But if there are lots of fp operations you're not showing, then an error can gradually get larger. And with any finite precision, you have the risk from things such as subtracting two nearly-equal values, which will reduce the final precision. If you need more than 18, then go to the Decimal module, which lets you set the precision to arbitrary levels. You will see a substantial slowdown, of course, if you set the precision very high. if that becomes a problem, consider CPython 3.3, which has optimized that module. But try not to change too many things at once, as there are lots of changes between 2.7 and 3.3. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 29/10/12 20:46, John Collins wrote: Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; Decimal has a specific meaning in Python different to how you appear to be using it. It looks to me like you are working with floats rather than decimals. If the difference means nothing to you, don't worry too much about it at this stage. from math import pi, asin, atan2, cos, sin, sqrt from math import pi, asin, atan2, cos, sin, sqrt That line appears duplicated. You can delete one of those lines. from crosspoint import crosspoint crosspoint appears to be a custom Python program that we know nothing about, apart from what you tell us. [...] I am not sure what == means, In Python, = is used for assignment: x = 1 means let x be a name for the value 1. == is used for equality testing: x == 2 returns False, because x does not equal 2; but x == 1 returns True, because x does currently equal 1. nor if any 'special' maths functions are called from crosspoint.py (to me, it appears not?), Nor to me. so, as I understand it, the from math import line *is* the 'math engine' if you will, and is the source of the 12 sig fig limit, yes? Almost. The from math import blah... line extracts a bunch of maths functions from the math library and makes them available to your program. The number of significant figures is more fundamental that that; your operating system understands about floating point numbers (so-called C doubles) with 53 *binary* significant figures, or about 17 *decimal* figures. So I'm not sure why you think there are only 12. One other odd thing that occurs, is when the scripts are run, a weird, small, non ASCII file called crosspoint.pyc is created? Is this the interpreter 'compiling' crosspoint.py ( either before, during, or after?) the 2nd script calls it? Yes. Sorry to bother, but if I can squeeze out *at least* 15 sig figs, You need to show us how the output is generated in the first place. (30 or more would be better!) Not a chance without some major changes to your program. I can't say how major without seeing more of your program. I'd be a happy camper! XNumbers addon for Excel allows over 200 sig figs by switching to base 256 IIRC. It is this with which I'd like to examine the output of these pyto scripts at finer resolution, if that can be done in python??? Well, yes, but only with some significant changes -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave Did you really leave two very-similar messages 3 minutes apart? Or are you using a broken gateway, like Google-groups, and it hiccoughed? Sorry, I didn't intend to - flunky LH mouse microswitch! Without knowing the type of the arguments being passed to the crosspoint() function, we cannot say. I can GUESS that they are int, long, or float. But you can find that out by examining the source that's calling it. Judging from the comments, I might guess they're int or long, and if so, only the division being done in the function produces floats. If that's the case, then you're limited to float's precision. if they are some other type (eg. Decimal), then indeed there might be special functions being called. Well, the two scripts are only about an email page long each, shall I post them? That import gets you access to the particular symbols it imports. Normal arithmetic on floats is already built in, and doesn't need an import. Right! Thanks. I'm assuming you're using CPython, and you say it's on XP. So presumably you're running an Intel (or Intel-compatible) processor with binary floating point built-in. That processor is the limit of float values in normal use. It's good to about 18 digits. Sure, 32 bit uproc, intrinsic binary limit. Exactly. It's a side-effect of the first import of the module. On subsequent imports, the pyc file is used, unless the py file has been modified meanwhile. Ah! Thanks! 18 digits is what you should get if the code is as I describe. But if there are lots of fp operations you're not showing, then an error can gradually get larger. And with any finite precision, you have the risk from things such as subtracting two nearly-equal values, which will reduce the final precision. AFAIK, it's all FP. inputs are integers, outputs range from -2. to 2. If you need more than 18, then go to the Decimal module, which lets you set the precision to arbitrary levels. You will see a substantial slowdown, of course, if you set the precision very high. if that becomes a problem, consider CPython 3.3, which has optimized that module. But try not to change too many things at once, as there are lots of changes between 2.7 and 3.3. I think I'll need to from what you have said / pointed out - ie, for in excess of 'machine' precision, one needs to change base 10 floats to a higher base, do foo, then come back. Sounds daunting! John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Pipes
Please give me sample python program that works with python31 Thanks Regards, Ganesh Manal. As soon as your dream become stronger than your doubts and fears , Your dream begins to manifest . ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
On 29 Oct 2012 02:30, Saad Javed sbja...@gmail.com wrote: I've come up with this: try: sys.argv[1] x = sys.argv[1] main(x) except IndexError: main(x) It works but seems hackish. Saad Saad, The first sys.argv is not needed. Notice how i have replied below the text i am quoting? That is the preference of most on the list. Best, Brian Vdb ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
John Collins wrote: Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; [On modern hardware] Python uses IEEE 754 double-precision http://en.wikipedia.org/wiki/Double_precision internally which gives 15 to 17 digits. But of course errors may accumulate. def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2): Give the intersection point of the (possibly extrapolated) lines\n\ segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2). dxa = xa2-xa1 dya = ya2-ya1 dxb = xb2-xb1 dyb = yb2-yb1 if dya * dxb == dxa * dyb: return None if dxa == 0: return (xa1, (xa1 - xb1) * dyb / dxb + yb1) if dxb == 0: return (xb1, (xb1 - xa1) * dya / dxa + ya1) if dya == 0: return ((ya1 - yb1) * dxb / dyb + xb1, ya1) if dyb == 0: return ((yb1 - ya1) * dxa / dya + xa1, yb1) det = dya * dxb - dyb * dxa xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1 ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1 return (xtop / det, ytop / det) I am not sure what == means, Equality. 1 == 0 False 1 == 1 True Because of rounding errors this is a dangerous operation for floating point numbers: print 1.0 == .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 False nor if any 'special' maths functions are called from crosspoint.py (to me, it appears not?), so, as I understand it, the from math import line *is* the 'math engine' if you will, and is the source of the 12 sig fig limit, yes? It is a toolbox rather than an engine. math is basically a wrapper around the C library, and these functions all use C's double and [most of the time] your hardware's floating point unit. One other odd thing that occurs, is when the scripts are run, a weird, small, non ASCII file called crosspoint.pyc is created? Is this the interpreter 'compiling' crosspoint.py ( either before, during, or after?) the 2nd script calls it? Yes, Python compiles the source to bytecode before it executes it, and for all modules except the main script this bytecode is cached in a .pyc file. Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30 or more would be better!) I'd be a happy camper! As you correctly observed crospoints() uses only +-*/ and ==, so you can feed it every type that supports these operations (this is called duck typing). For example: from fractions import Fraction from crosspoint import crosspoint crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) (Fraction(5, 7), Fraction(1, 3)) p = crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) print %s, %s % p 5/7, 1/3 Yay, infinite precision ;) Of more practical relevance may be something like gmpy http://code.google.com/p/gmpy/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Pipes
Ganesh Manal wrote: Please give me sample python program that works with python31 $ touch sample.py $ cat sample.py $ python3 sample.py So the minimal python3 program is an empty file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Steve, Thanks. From mkpoints.py 32 32.txt here's a sample of the output -0.396087591388 -0.781284022758 0.482400140683 -0.967387012461 -0.0838047084421 -0.239037944614 0.0208969821213 -0.489420208746 0.871797668848 0.887250003871 -0.258893773768 -0.38178717178 0.426352071227 -0.457758408728 -0.780180203927 0.612061168992 -0.280383142359 0.739436555016 -0.887250003871 0.258893773768 0.38178717178 -0.0971745158475 -0.994342015264 -0.0429076933695 -0.120898756509 -0.759794654167 -0.638823586113 -0.0208969821213 0.489420208746 -0.871797668848 0.482396765336 -0.834880934468 -0.265079584379 0.66383194755 0.726669941038 0.176855710123 from nfaces.py 32.txt 32fa.txt here's a sample of the output point vertex_0_2_12 -0.0288974102653 -0.851924110364 0.66948446135 point vertex_13_24_27 -0.122445373457 1.00045419254 0.398644871129 point vertex_0_7_15 -0.482610585141 -0.963539328269 0.1161816686 point vertex_3_10_17 0.848541556491 -0.639691741968 -0.213520247975 point vertex_1_6_14 -1.05498774772 0.248634080415 -0.00106786881656 point vertex_13_24_31 -0.291794484064 0.826881428947 0.637135994637 point vertex_1_6_25 -1.07023716261 -0.0479998647263 0.164643927545 point vertex_3_17_28 1.05498774772 -0.248634080415 0.00106786881656 point vertex_1_15_25 -0.975134617659 -0.4675255693 -0.073154040374 point vertex_4_8_10 0.291794484064 -0.826881428947 -0.637135994637 point vertex_9_19_20 -0.400242088946 0.638705226984 -0.778897359983 normal face_30 -0.617395768043 -0.35935879 -0.699844161834 face face_31 vertex_21_29_31 face face_31 vertex_13_21_31 face face_31 vertex_13_24_31 face face_31 vertex_6_24_31 face face_31 vertex_6_29_31 normal face_31 -0.426352071227 0.457758408728 0.780180203927 As you can see, there are exactly 12 significant figures. BTW, I did not write either script, I can post them, if you think doing so may show where it may be possible to escape to decimal as you say, perhaps? Decimal has a specific meaning in Python different to how you appear to be using it. It looks to me like you are working with floats rather than decimals. Right. from math import pi, asin, atan2, cos, sin, sqrt from math import pi, asin, atan2, cos, sin, sqrt Two different scripts. crosspoint appears to be a custom Python program that we know nothing about, apart from what you tell us. I posted it in it's entirety. == is used for equality testing: x == 2 returns False, because x does not equal 2; but x == 1 returns True, because x does currently equal 1. Ah! Thanks! Almost. The from math import blah... line extracts a bunch of maths functions from the math library and makes them available to your program. I'm seeing this now. Python does minimal things, extras are called in only as needed. The number of significant figures is more fundamental that that; your operating system understands about floating point numbers (so-called C doubles) with 53 *binary* significant figures, or about 17 *decimal* figures. So I'm not sure why you think there are only 12. Sure. But see the above, from Py 2.7.2, it's precisely 12 sig.figs.! You need to show us how the output is generated in the first place. Done, above. Not a chance without some major changes to your program. I was afraid of this. I can't say how major without seeing more of your program. Well, OK, here's the first, mkpoints.py #!/usr/bin/env python # Distribute a set of points randomly across a sphere, allow them # to mutually repel and find equilibrium. import sys import string import random from math import pi, asin, atan2, cos, sin, sqrt args = sys.argv[1:] if len(args) 0: n = string.atoi(sys.argv[1]) args = args[1:] else: n = 7 if len(args) 0: outfile = open(args[0], w) args = args[1:] else: outfile = sys.stdout points = [] def realprint(a): for i in range(len(a)): outfile.write(str(a[i])) if i len(a)-1: outfile.write( ) else: outfile.write(\n) def pprint(*a): realprint(a) for i in range(n): # Invent a randomly distributed point. # # To distribute points uniformly over a spherical surface, the # easiest thing is to invent its location in polar coordinates. # Obviously theta (longitude) must be chosen uniformly from # [0,2*pi]; phi (latitude) must be chosen in such a way that # the probability of falling within any given band of latitudes # must be proportional to the total surface area within that # band. In other words, the probability _density_ function at # any value of phi must be proportional to the circumference of # the circle around the sphere at that latitude. This in turn # is proportional to the radius out from the sphere at that # latitude, i.e. cos(phi). Hence the cumulative probability # should be proportional to the integral of that, i.e. sin(phi) # - and since we know the cumulative probability needs to be # zero at -pi/2 and 1 at +pi/2, this tells us it has to be #
Re: [Tutor] Python Pipes
On 29/10/2012 10:33, Ganesh Manal wrote: Please give me sample python program that works with python31 Thanks Regards, Ganesh Manal. As soon as your dream become stronger than your doubts and fears , Your dream begins to manifest . Please give me a signed and dated cheque with the areas for the payment left blank so that I can fill them in myself. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 10/29/2012 06:32 AM, John Collins wrote: Hi Dave Did you really leave two very-similar messages 3 minutes apart? Or are you using a broken gateway, like Google-groups, and it hiccoughed? Sorry, I didn't intend to - flunky LH mouse microswitch! I was only concerned that there was some correction in one of the messages. And since there was only 3 minutes between them, i didn't know which might be the corrected one. They showed up here out of order. I responded to the one with the later timestamp. SNIP Well, the two scripts are only about an email page long each, shall I post them? Just post one of them. Otherwise, things can get very confusing. I'm assuming you're using CPython, and you say it's on Exactly. It's a side-effect of the first import of the module. On subsequent imports, the pyc file is used, unless the py file has been modified meanwhile. Ah! Thanks! XP. So presumably you're running an Intel (or Intel-compatible) processor with binary floating point built-in. That processor is the limit of float values in normal use. It's good to about 18 digits. Sure, 32 bit uproc, intrinsic binary limit. Actually, it's 64 bits. 32 bit fp wouldn't get you anywhere near 18 digits. SNIP AFAIK, it's all FP. inputs are integers, outputs range from -2. to 2. Since the inputs to that function are ints, then the output will be IEEE floats. that also means that the == comparisons in the crosspoint() function are precise. If you need more than 18, then go to the Decimal module, which lets you set the precision to arbitrary levels. You will see a substantial slowdown, of course, if you set the precision very high. if that becomes a problem, consider CPython 3.3, which has optimized that module. But try not to change too many things at once, as there are lots of changes between 2.7 and 3.3. I think I'll need to from what you have said / pointed out - ie, for in excess of 'machine' precision, one needs to change base 10 floats to a higher base, do foo, then come back. Sounds daunting! Actually, the base change is already happening. Using Decimal would probably reduce the number of base changes. And if you create the numbers as Decimal objects, then they'll propagate through the crosspoint() function correctly.However, even though the decimal module supports log and sqrt, I don't know how to do trig with it. Incidentally, I didn't suggest the fractions module, since you're presumably going to be doing trig on the results, so I don't see the benefit. BTW, I misspoke earlier. The module name is decimal. The class name within that module is Decimal. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Peter, Thanks. [On modern hardware] Python uses IEEE 754 double-precision http://en.wikipedia.org/wiki/Double_precision internally which gives 15 to 17 digits. But of course errors may accumulate. As in my previous, this script seems to output precisely 12 significant not 15 and not 17. ??? 15 and I'd be happier right now, as it matches Excel's precision there, 'as it is'. Equality. Right, in a 1,0 sense. Because of rounding errors this is a dangerous operation for floating point numbers: print 1.0 == .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 False I take it that is because binary for .1 is a repeating sequence, yes? It is a toolbox rather than an engine. Ah ha! *Now* I'm getting it! math is basically a wrapper around the C library, and these functions all use C's double and [most of the time] your hardware's floating point unit. Right! Yes, Python compiles the source to bytecode before it executes it, and for all modules except the main script this bytecode is cached in a .pyc file. That nails it (as I was wondering, just now, why the primary scripts remained intact). As you correctly observed crospoints() uses only +-*/ and ==, so you can feed it every type that supports these operations (this is called duck typing). For example: from fractions import Fraction from crosspoint import crosspoint crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) (Fraction(5, 7), Fraction(1, 3)) p = crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) print %s, %s % p 5/7, 1/3 Yay, infinite precision ;) You just lost me. Of more practical relevance may be something like gmpy http://code.google.com/p/gmpy/ I've just had a peek. Looks like what I need. Haven't a clue if I'll understand how to 'patch it in' to the scripts. Doco read time! John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 10/29/2012 06:54 AM, John Collins wrote: Hi Steve, Thanks. From mkpoints.py 32 32.txt here's a sample of the output -0.396087591388 -0.781284022758 0.482400140683 -0.967387012461 -0.0838047084421 -0.239037944614 0.0208969821213 -0.489420208746 0.871797668848 0.887250003871 -0.258893773768 -0.38178717178 0.426352071227 -0.457758408728 -0.780180203927 0.612061168992 -0.280383142359 0.739436555016 -0.887250003871 0.258893773768 0.38178717178 -0.0971745158475 -0.994342015264 -0.0429076933695 -0.120898756509 -0.759794654167 -0.638823586113 -0.0208969821213 0.489420208746 -0.871797668848 0.482396765336 -0.834880934468 -0.265079584379 0.66383194755 0.726669941038 0.176855710123 from nfaces.py 32.txt 32fa.txt here's a sample of the output point vertex_0_2_12 -0.0288974102653 -0.851924110364 0.66948446135 point vertex_13_24_27 -0.122445373457 1.00045419254 0.398644871129 point vertex_0_7_15 -0.482610585141 -0.963539328269 0.1161816686 point vertex_3_10_17 0.848541556491 -0.639691741968 -0.213520247975 point vertex_1_6_14 -1.05498774772 0.248634080415 -0.00106786881656 point vertex_13_24_31 -0.291794484064 0.826881428947 0.637135994637 point vertex_1_6_25 -1.07023716261 -0.0479998647263 0.164643927545 point vertex_3_17_28 1.05498774772 -0.248634080415 0.00106786881656 point vertex_1_15_25 -0.975134617659 -0.4675255693 -0.073154040374 point vertex_4_8_10 0.291794484064 -0.826881428947 -0.637135994637 point vertex_9_19_20 -0.400242088946 0.638705226984 -0.778897359983 normal face_30 -0.617395768043 -0.35935879 -0.699844161834 face face_31 vertex_21_29_31 face face_31 vertex_13_21_31 face face_31 vertex_13_24_31 face face_31 vertex_6_24_31 face face_31 vertex_6_29_31 normal face_31 -0.426352071227 0.457758408728 0.780180203927 As you can see, there are exactly 12 significant figures. Not true. That's just what it was truncated to upon output. If you want to show 15 digits, then use formatted output instead of str() inside the realprint() function. SNIP def realprint(a): for i in range(len(a)): outfile.write(str(a[i])) if i len(a)-1: outfile.write( ) else: outfile.write(\n) output.write({0:.15f}.format(x)) You may want to play with the format a bit to get it the way you actually want it. Note that the format will happily output nonsense digits beyond the end of the available precision, so you have to do your own figuring before deciding what to display. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave, Thanks, more insights! I was only concerned that there was some correction in one of the messages. And since there was only 3 minutes between them, i didn't know which might be the corrected one. They showed up here out of order. I responded to the one with the later timestamp. No, mia culpa. Just post one of them. Otherwise, things can get very confusing. Done. Actually, it's 64 bits. 32 bit fp wouldn't get you anywhere near 18 digits. Darn, of course, you're right! Senior moment for me! Since the inputs to that function are ints, then the output will be IEEE floats. that also means that the == comparisons in the crosspoint() function are precise. THAT is a very valuable insight Dave, thanks! Actually, the base change is already happening. Using Decimal would probably reduce the number of base changes. And if you create the numbers as Decimal objects, then they'll propagate through the crosspoint() function correctly.However, even though the decimal module supports log and sqrt, I don't know how to do trig with it. Well, as trig is *core essential* to polyhedra maths, I *have* to use *lots* of it! Incidentally, I didn't suggest the fractions module, since you're presumably going to be doing trig on the results, so I don't see the benefit. Yes. Core maths is +,-,*,/,sin,cos,tan (and their inverses), sqrt, ^2,^3, (ie, exponentials), etc off hand. BTW, I misspoke earlier. The module name is decimal. The class name within that module is Decimal. A minor thing to me, a non programmer, but I do understand that being very precise is very important to programmers, so thank you! John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 10/29/2012 07:19 AM, John Collins wrote: snip Equality. Right, in a 1,0 sense. Because of rounding errors this is a dangerous operation for floating point numbers: print 1.0 == .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 False I take it that is because binary for .1 is a repeating sequence, yes? Yes. Since it cannot be represented exactly, you get a quantization error. snip As you correctly observed crospoints() uses only +-*/ and ==, so you can feed it every type that supports these operations (this is called duck typing). For example: from fractions import Fraction from crosspoint import crosspoint crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) (Fraction(5, 7), Fraction(1, 3)) p = crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1)) print %s, %s % p 5/7, 1/3 Yay, infinite precision ;) You just lost me. If you don't use any transcendental functions, then a fraction has no quantization error. It's totally precise. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave, Not true. That's just what it was truncated to upon output. If you want to show 15 digits, then use formatted output instead of str() inside the realprint() function. BIG light bulb moment! I had no idea the str() statement was truncating! I *did* search the script for 12 or trunc (being a newbie!) and saw nothing. Hence my silly questions tonight! SNIP def realprint(a): for i in range(len(a)): outfile.write(str(a[i])) if i len(a)-1: outfile.write( ) else: outfile.write(\n) output.write({0:.15f}.format(x)) You may want to play with the format a bit to get it the way you actually want it. Note that the format will happily output nonsense digits beyond the end of the available precision, so you have to do your own figuring before deciding what to display. Hmm, well, I did modify the original script by setting the convergence test value to 2.005e-16 up from 1e-6, s, I 'guess' 15 sig.figs. will be OK. I'll have a go! That's 3 orders of magnitude better for a few key strokes! Great! (maybe...) John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave, You just lost me. If you don't use any transcendental functions, then a fraction has no quantization error. It's totally precise. Ah ha! Another light bulb moment - two in one night! Thank you Dave, and all! John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave, Not silly at all. I didn't realize str(float) would truncate to 12 digits either. I found out by experimenting (with 2.7) in the interpreter. Very gracious of you to say, and generous of you to trouble yourself to experiment - thank you very much! Note that it may differ from version to version. And that's another reason to use format. Excellent point! But please don't just take the format string I supplied as right. It is if you always want 15 decimal digits to the right of the decimal point. But if you have a number like 50 thousand, then many of those digits to the right are invalid. Indeed! As you saw, some outputs are, and really must be output as integers. A 1 with a decimal point followed by 15 0's would make a real mess of the face/vertex designation table. So I have to be careful where I invoke output.write({0:.15f}.format(x)) or similar, ie, that it operates only on the values I'd like output that way. Which raises a question. Is the command 'persistent'? In other words, if I use it early on, but then wish to output integers, has it 'died after use', do I need to 'kill it after use', or will python just default back to what it sees next? I know this sounds silly, but to me the command 'looks' like it's setting a 'hidden pyton variable' to 15f which may need to be explicitly revoked, or not,...??? John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 10/29/2012 08:14 AM, John Collins wrote: snip But please don't just take the format string I supplied as right. It is if you always want 15 decimal digits to the right of the decimal point. But if you have a number like 50 thousand, then many of those digits to the right are invalid. Indeed! As you saw, some outputs are, and really must be output as integers. A 1 with a decimal point followed by 15 0's would make a real mess of the face/vertex designation table. So I have to be careful where I invoke output.write({0:.15f}.format(x)) or similar, ie, that it operates only on the values I'd like output that way. Which raises a question. Is the command 'persistent'? In other words, if I use it early on, but then wish to output integers, has it 'died after use', do I need to 'kill it after use', or will python just default back to what it sees next? I know this sounds silly, but to me the command 'looks' like it's setting a 'hidden pyton variable' to 15f which may need to be explicitly revoked, or not,...??? John. Valid question. However, there are no hidden variables used in format. Each time you invoke the format method (it's a method of str), it starts from scratch using only its current arguments. i can't think of any sense in which 'default' fits here, either. You do really need to study the format spec, to see what other parameters may be more useful. What I supplied is great if all the digits are to the right of the decimal. Note, you can also use format on integers, in order to make a fixed number of columns, for example. Or to get leading zeroes. Or whatever. And realize that the format does not have to be inside the write. So you can format to a string, then post-process in some way, before sending to the write method. Incidentally, One of numpy or gmpy is probably a very good idea for you. But as I have no experience with either, it just didn't occur to me. So I'm glad Peter mentioned one of them. The only catch I know of is it's an external dependency, meaning you have to download and install it into the Python search path. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Dave, Valid question. However, there are no hidden variables used in format. Each time you invoke the format method (it's a method of str), it starts from scratch using only its current arguments. i can't think of any sense in which 'default' fits here, either. Thanks, that's somewhat of a relief. In nfaces.py which outputs like this SNIP point vertex_11_22_27 0.482610585141 0.963539328269 -0.1161816686 point vertex_11_18_28 0.894075981233 0.461195737945 0.403417680839 face face_0 vertex_0_2_29 face face_0 vertex_0_25_29 face face_0 vertex_0_15_25 face face_0 vertex_0_7_15 face face_0 vertex_0_7_12 face face_0 vertex_0_2_12 normal face_0 -0.396087591388 -0.781284022758 0.482400140683 face face_1 vertex_1_15_30 SNIP there are nested outfile.write commands with logical tests! Best now I try your suggestions - experiment, I can't break it(!), and if after a sleepless night, it's all pea soup, I'll log back in with this marvellous group of very knowledgeable and helpful folks! You do really need to study the format spec, to see what other parameters may be more useful. What I supplied is great if all the digits are to the right of the decimal. Agreed. Note, you can also use format on integers, in order to make a fixed number of columns, for example. Or to get leading zeroes. Or whatever. Interesting... And realize that the format does not have to be inside the write. So you can format to a string, then post-process in some way, before sending to the write method. Very interesting! Incidentally, One of numpy or gmpy is probably a very good idea for you. But as I have no experience with either, it just didn't occur to me. So I'm glad Peter mentioned one of them. The only catch I know of is it's an external dependency, meaning you have to download and install it into the Python search path. Yes! A while back, Ramit mentioned; P.S. If you want large amount of accuracy with number crunching, you may want to look into using fixed-precision or binary math libraries. Try looking at scipy/numpy or using Decimal instead of floating-point numbers. (This is just a suggestion and may be incorrect because I have not yet needed such accuracy. ) Which I just searched for and dug up! Right, I'm off to bash this script like a beginner, and see what emerges! :) Thanks for so many insights in one night - terrific! Wish I'd picked this language up *years* ago - it's so foreign to me now, yet so beautifully useful! Cheers, John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Pipes
Suggestion that you restate your request in the form of a question that is less generic and more specific to what you are looking for. On Mon, Oct 29, 2012 at 6:33 AM, Ganesh Manal manalgan...@gmail.com wrote: Please give me sample python program that works with python31 Thanks Regards, Ganesh Manal. As soon as your dream become stronger than your doubts and fears , Your dream begins to manifest . ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Pipes
On 10/29/2012 3:33 AM, Ganesh Manal wrote: Please give me sample python program that works with python31 Start with the tutorial at http://docs.python.org/3/tutorial/index.html It'll step you through lots of sample python scripts. Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
On 29 October 2012 06:06, Saad Javed sbja...@gmail.com wrote: Hi, #!/usr/bin/env python import sys x = 'Saad is a boy' def main(x): a = [] b = x.split(' ') for item in b: a.append(item) print a if __name__ == '__main__': x = sys.argv[1] main(x) How can I make this program run with the default value of x if I don't specify an argument at the command line? My preference is to use Python's default function argument mechanism to fill in the missing values: def main(x, y='default'): print(x) print(y) if __name__ == __main__: main(sys.argv[1:]) This is the quickest way to get what you want. For a proper script, though, I would use an argument parser such as argparse. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
On 29 October 2012 13:32, Oscar Benjamin oscar.j.benja...@gmail.com wrote: def main(x, y='default'): print(x) print(y) if __name__ == __main__: main(sys.argv[1:]) A quick correction. That should be (note the *): if __name__ == __main__: main(*sys.argv[1:]) Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On Mon, Oct 29, 2012 at 7:05 AM, Dave Angel d...@davea.name wrote: Actually, it's 64 bits. 32 bit fp wouldn't get you anywhere near 18 digits. A double has 53 bits of precisions, which is 53*log10(2) =~ 15.955 decimal digits. However, one often sees the numbers 15 and 17 quoted for the precision. It depends. A double is guaranteed to accurately store a string with 15 decimal digits (round trip). But each 15-digit decimal string maps to many doubles: from struct import unpack format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.15f') '0.100' format(unpack('d', '\xbd\x99\x99\x99\x99\x99\xb9?')[0], '.15f') '0.100' 0xbd - 0x76 + 1 # doubles that round to 0.100 72 (Note: my Intel processor is little endian, so the least significant byte is index 0 in the packed double, such as '\x76'.) However, to exactly represent each double requires 17 decimal digits: format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.17f') '0.09951' format(unpack('d', '\x77\x99\x99\x99\x99\x99\xb9?')[0], '.17f') '0.09952' Python says the precision is 15 decimal digits: import sys sys.float_info.mant_dig # bits of precision 53 sys.float_info.dig# decimal digits 15 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 29/10/2012 12:00, Dave Angel wrote: Not silly at all. I didn't realize str(float) would truncate to 12 digits either. I found out by experimenting (with 2.7) in the interpreter. Note that it may differ from version to version. And that's another reason to use format. It's 16 digits with 3.3.0. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Pipes
On Mon, Oct 29, 2012 at 6:33 AM, Ganesh Manal manalgan...@gmail.com wrote: Please give me sample python program that works with python31 Re: Python Pipes If you're looking to pipe data to, from, and between processes, look at the subprocess module: http://docs.python.org/release/3.1/library/subprocess If you want something specific to a Unix shell, look at the pipes module: http://docs.python.org/release/3.1/library/pipes If you want your own program to behave differently when stdin/stdout are piped, use isatty(): import sys sys.stdin.isatty() True sys.stdout.isatty() True http://docs.python.org/release/3.1/library/io#io.IOBase.isatty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hello, Just checked my py, and 15 was the report! Wish I had known that factoid - thank you, for a very complete coverage of the broader intrinsic 'machine' + system precision - it actually makes sense to me now - it's a calculation! On 30/10/2012 2:02 AM, eryksun wrote: SNIP A double has 53 bits of precisions, which is 53*log10(2) =~ 15.955 decimal digits. However, one often sees the numbers 15 and 17 quoted for the precision. It depends. A double is guaranteed to accurately store a string with 15 decimal digits (round trip). But each 15-digit decimal string maps to many doubles: from struct import unpack format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.15f') '0.100' format(unpack('d', '\xbd\x99\x99\x99\x99\x99\xb9?')[0], '.15f') '0.100' 0xbd - 0x76 + 1 # doubles that round to 0.100 72 (Note: my Intel processor is little endian, so the least significant byte is index 0 in the packed double, such as '\x76'.) However, to exactly represent each double requires 17 decimal digits: format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.17f') '0.09951' format(unpack('d', '\x77\x99\x99\x99\x99\x99\xb9?')[0], '.17f') '0.09952' Python says the precision is 15 decimal digits: import sys sys.float_info.mant_dig # bits of precision 53 sys.float_info.dig# decimal digits 15 Regs, John. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 29/10/2012 12:14, John Collins wrote: Indeed! As you saw, some outputs are, and really must be output as integers. A 1 with a decimal point followed by 15 0's would make a real mess of the face/vertex designation table. So I have to be careful where I invoke output.write({0:.15f}.format(x)) or similar, ie, that it operates only on the values I'd like output that way. If you're more comfortable with C you can use printf style formatting see http://docs.python.org/2/library/stdtypes.html#string-formatting -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Thanks Mark. I 'stuck' with 2.7.2 for these old scripts, unless I want to totally rewrite them. They are so elegant, this would realy amount to starting from scratch. I get 15 reported, and that's going to be sufficient for these 'as they are'. For more, it's a go back to year zero exercise I feel. John. On 30/10/2012 2:15 AM, Mark Lawrence wrote: SNIP It's 16 digits with 3.3.0. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
Hi Mark, Thanks. I wouldn't know C if I fell over it. Until recently, the *only* language I'd ever used was (HP, GW)BASIC aside from Fortran 101, 3 decades ago! John. On 30/10/2012 2:45 AM, Mark Lawrence wrote: SNIP If you're more comfortable with C you can use printf style formatting see http://docs.python.org/2/library/stdtypes.html#string-formatting ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 29/10/2012 11:39, John Collins wrote: Hi Dave, BTW, I misspoke earlier. The module name is decimal. The class name within that module is Decimal. A minor thing to me, a non programmer, but I do understand that being very precise is very important to programmers, so thank you! John. If you had to change some code and use the Decimal class from the decimal module it would soon become a major issue as Python is case sensitive, even on Windows. Just hoping I've got my dS in the RiGhT cAsE :) -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On Mon, Oct 29, 2012 at 11:15 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 29/10/2012 12:00, Dave Angel wrote: Not silly at all. I didn't realize str(float) would truncate to 12 digits either. I found out by experimenting (with 2.7) in the interpreter. It's 16 digits with 3.3.0. It was changed to use the repr in 3.2. See tp_repr/tp_str in PyFloat_Type: http://hg.python.org/cpython/file/a222a015e28d/Objects/floatobject.c#l1849 From What’s New In Python 3.2: http://docs.python.org/release/3.2/whatsnew/3.2#other-language-changes The str() of a float or complex number is now the same as its repr(). Previously, the str() form was shorter but that just caused confusion and is no longer needed now that the shortest possible repr() is displayed by default As repr() does, it chooses the minimum number of digits required to round exactly to the original double: repr with 1 digit: pack('d', 0.1) '\x9a\x99\x99\x99\x99\x99\xb9?' unpack('d', '\x9a\x99\x99\x99\x99\x99\xb9?')[0] 0.1 repr with 16 digits: pack('d', 0.0995) 'v\x99\x99\x99\x99\x99\xb9?' unpack('d', 'v\x99\x99\x99\x99\x99\xb9?')[0] 0.0995 repr with 17 digits: pack('d', 0.10002) '\x9b\x99\x99\x99\x99\x99\xb9?' unpack('d', '\x9b\x99\x99\x99\x99\x99\xb9?')[0] 0.10002 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Passing Variables
David Hutto wrote: #A little more complex in terms of params: def SwapCaseAndCenter(*kwargs): if upper_or_lower == upper: print a_string.center(center_num).upper() if upper_or_lower == lower: print a_string.center(center_num).lower() a_string = raw_input(Give me a word, or letter: ) upper_or_lower = raw_input(upper, or lower character(s): ) center_num = int(raw_input(Where should number be centered?: )) SwapCaseAndCenter(a_string, upper_or_lower, center_num) This function is using the global variables for each of its variables. To use the versions passed in you need to define the names from kwargs; the name kwargs is usually used in reference to a keyword arguments which should be denoted by double asterisk instead of a single one. In this case kwargs is confusingly a positional list of arguments (sometimes referred to as args instead). For a function called SwapCaseAndCenter, I see it doing no case swapping unless it refers to changing the entire string to a specific case? At the very least, no centering is being done. To format I use string formatting[0] which has its own syntax[1]. '{0:^40}'.format( 'test' ) # The below line is the repr ' test ' '{1:^{0}}'.format( 40, 'test' ) # Dynamically generate width ' test ' '{0:^{1}}'.format( 'test', 40 ) ' test ' [0]: http://docs.python.org/2/library/string.html#formatstrings [1]: http://docs.python.org/2/library/string.html#formatspec Ramit Prasad This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] greater precision?
On 29 October 2012 10:19, Dave Angel d...@davea.name wrote: On 10/29/2012 05:49 AM, John Collins wrote: Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30 or more would be better!) I'd be a happy camper! XNumbers addon for Excel allows over 200 sig figs by switching to base 256 IIRC. It is this with which I'd like to examine the output of these pyto scripts at finer resolution, if that can be done in python??? Best Regards, John Collins. 18 digits is what you should get if the code is as I describe. But if there are lots of fp operations you're not showing, then an error can gradually get larger. And with any finite precision, you have the risk from things such as subtracting two nearly-equal values, which will reduce the final precision. I wouldn't describe it as 18 digits of precision since it fails for computations that require only 17 digits of precision: 1e-16 1e-16 1 + 1e-16 - 1 0.0 If you need more than 18, then go to the Decimal module, which lets you set the precision to arbitrary levels. You will see a substantial slowdown, of course, if you set the precision very high. if that becomes a problem, consider CPython 3.3, which has optimized that module. But try not to change too many things at once, as there are lots of changes between 2.7 and 3.3. I don't really understand why so much precision is needed but if I were trying to improve it I would use the fractions module. The Fraction type from the fractions module has unlimited precision: from fractions import Fraction 1 + Fraction('1e-16') - 1 Fraction(1, 1) 1 + Fraction('1e-256') - 1 Fraction(1, 1) To use this you would do the same as for the decimal module: convert all of your numbers to Fraction type and pass the Fraction objects into the function that performs computation with them. Of course if you start out with floats and convert them to fractions then you will still only have 15 digits of precision so if you really want unlimited precision you need to convert the numbers to fractions at the point when their values are known exactly and not use floats anywhere. This means that your computations are exact but you still need to choose a precision to output the numbers in decimal (unless you're happy with fractions as output). If you want 256 digit decimal output you can do: import decimal decimal.getcontext().prec = 256 f = 1 + Fraction('1e-255') d = decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator) print(d) 1.001 Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] calling a module fails
Methinks I'm missing something obvious, but can't quite put my finger on it. If, in the interpreter, I enter the following code: def hungry(batVolt): if batVolt 94: return (I am not hungry at the moment) elif 64 batVolt 95: return (I'm starting to get hungry) else: return (I'm hungry!) and then run hungry(98) with 98 just being an example of the many numbers I tried when testing this, I get the return I expected and all is well. If, however, I save the above in a file named hungry.py, then import hungry, I get an error, as follows: import hungry hungry(96) Traceback (most recent call last): File stdin, line 1, in module TypeError: 'module' object is not callable So what am I missing? Someone do please point out the obvious. ;-) regards, Richard -- sic gorgiamus allos subjectatos nunc ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling a module fails
On 10/29/2012 09:00 PM, richard kappler wrote: Methinks I'm missing something obvious, but can't quite put my finger on it. If, in the interpreter, I enter the following code: def hungry(batVolt): if batVolt 94: return (I am not hungry at the moment) elif 64 batVolt 95: return (I'm starting to get hungry) else: return (I'm hungry!) and then run hungry(98) with 98 just being an example of the many numbers I tried when testing this, I get the return I expected and all is well. If, however, I save the above in a file named hungry.py, then import hungry, I get an error, as follows: import hungry hungry(96) Traceback (most recent call last): File stdin, line 1, in module TypeError: 'module' object is not callable So what am I missing? Someone do please point out the obvious. ;-) regards, Richard I'd recommend NOT ever calling the module by the same name as one of the functions or classes in it. When you want to call a function in an external module, you have a choice of: import mymodule mymodule.myfunction(98) or from mymodule import myfunction myfunction(98) By using the same name, it isn't obvious to you that what you need is: hungry.hungry(98) -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling a module fails
On 30/10/12 12:00, richard kappler wrote: [...] If, however, I save the above in a file named hungry.py, then import hungry, I get an error, as follows: import hungry hungry(96) Traceback (most recent call last): File stdin, line 1, inmodule TypeError: 'module' object is not callable So what am I missing? Someone do please point out the obvious. ;-) You have a module called hungry and a function called hungry inside that, so to reach the inner hungry you need to do this: import hungry hungry.hungry(96) Which is no different from: import math math.cos(0.96) Python will never try to guess which inner function you want when you call a module directly, not even if the inner function has the same name as the module. You must always explicitly tell it which inner function you want. An alternative is this: from hungry import hungry # like from math import cos hungry(96) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor