Re: [Tutor] help
"Vickram" wrote I need help in translating a C++ code into python.. Can you help please? The python result is wrong because I may have misread the C++ code The C++ code is really just C code, there is virtualy no C++ stuff there. But that aside your translation is pretty faithful (too faithful with all those float() conversions). When you say it is "wrong" what exactly do you mean? You get different values as output? By how much? It looks like you need to do a detailed step by step walk through of the code and see if you have missed an operator or polarity or maybe have an off-by-one error in a loop. HTH, -- Alan Gauld 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] BLAS Implementation on Python
Am 08.03.2011 20:00, schrieb Alan Gauld: "Stefan Behnel" wrote He doesn't have to write it, as it is very obvious, that no Python code on earth (even written by Guido himself ;-)) stands a chance compared to Fortran or C. Look at this: There is one big proviso. The C or Fortran needs to be well written It's seriously hard to write computational Python code that is faster than C code, though. Agreed, it was the assertion that "no Python code on earth...stands a chance..." that I was objecting to. There are many areas where the C code would have to be pathologically bad to be beaten by Python, but there are plenty of places where only slightly inefficient C code can be competitive relatie to Python. Maybe there're those areas, but the top posters question is about reimplementing BLAS, which is a highly optimized package for linear algebra. And in this area no pure Python code on earth on any currently available Python implementation stands a chance performance wise to one of the C or Fortran implementations. Alan G. ___ 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] help
The first hundred pages of a thorough python tutorial, and a c++ tutorial should have you doing both of those quite well in a day or so. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Tue, Mar 8, 2011 at 6:38 PM, Vickram wrote: > The python result is wrong because I may have misread the C++ code Well, really, I suggest you read a tutorial on Python - you don't seem to be getting a hang on the basics, for example, there's no need for to use the float() function. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] BLAS Implementation on Python
"Stefan Behnel" wrote He doesn't have to write it, as it is very obvious, that no Python code on earth (even written by Guido himself ;-)) stands a chance compared to Fortran or C. Look at this: There is one big proviso. The C or Fortran needs to be well written It's seriously hard to write computational Python code that is faster than C code, though. Agreed, it was the assertion that "no Python code on earth...stands a chance..." that I was objecting to. There are many areas where the C code would have to be pathologically bad to be beaten by Python, but there are plenty of places where only slightly inefficient C code can be competitive relatie to Python. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] help
Hello I need help in translating a C++ code into python.. Can you help please? Please find attached the two codes. The python result is wrong because I may have misread the C++ code Thanks Vickram from mpmath import * mp.dps=5 c = mpf('299792.458') H0 = float(70) # Hubble constant (km/s/Mpc) - adjust according to taste OM = float(0.27) # Omega(matter) - adjust according to taste OL = float(0.73) # Omega(lambda) - adjust according to taste OR = float(0.42/(H0*H0)) #Omega(radiation) - this is the usual textbook value n=1 # Number of steps in the integral OK = float(1-OM-OR-OL) # Omega(k) defined as 1-OM-OR-OL HD = float(3.2616*c/H0/1000) # Hubble distance (billions of light years). See section 2 of Hogg # Redshift "z", Scale Factor "a", and its derivative "adot" DC =float(0) DCC=float(0) DT = float(0) DTT=float(0) a = float(0) adot = float(0) # The age and size of the universe z = input("Enter Redshift: ") #Ask for a redshift z for i in range(n,0,-1): # This loop is the numerical integration a = (float(i)-0.5)/n # Steadily decrease the scale factor# Comoving formula (See section 4 of Hogg, but I've added a radiation term too): adot = float(a)*sqrt(OM*pow(1/float(a) ,3)+OK*pow(1/float(a),2)+OL+OR*pow(1/float(a),4))# Note that "a" is equivalent to 1/(1+z) DCC = float(DCC) + 1/(float(a)*float(adot))/long(n) # Running total of the comoving distance DTT = float(DTT) + 1/float(adot)/n # Running total of the light travel time (see section 10 of Hogg) if a >=1/(1+z):# Collect DC and DT until the correct scale is reached DC = DCC # Comoving distance DC DT = DTT #Light travel time DT # Transverse comoving distance DM from section 5 of Hogg: if OK>0.0001: DM=(1/sqrt(OK))*sinh(sqrt(OK)*DC) elif OK<-0.0001: DM=(1/sqrt(fabs(OK)))*sin(sqrt(fabs(OK))*DC) else: DM=DC print a print adot print DT print DTT print DC print DCC age = HD*DTT# Age of the universe (billions of years) size = HD*DCC # Comoving radius of the observable universe DC = HD*DC # Comoving distance DA = HD*DM/(1+z) # Angular diameter distance (section 6 of Hogg) DL = HD*DM*(1+z) # Luminosity distance (section 7 of Hogg) DT = HD*DT # Light travel distance print"---" print "For Redshift",z,", Ho= ",H0,"km/s/Mpc, Omega_M=",OM,", Omega_L=",OL print "---" print "* Age of the universe now = ",age,"Gyr" print "* Age of the universe then = ",age-DT,"Gyr" print "* Comoving horizon of the universe now = ",size,"Gyr" print "* Comoving horizon of the universe then = ",size/(1+z),"Gyr" print "* Comoving distance of the source now = ",DC,"Gly" print "* Comoving distance of the source then = ",DC/(1+z),"Gly"# In a flat universe, this is equal to DA print "* Angular Diameter distance = ",DA,"Gly" print "* Luminosity distance = ",DL,"Gly" print "* Light Travel Time Distance= ",DT,"Gly" print "---" /* cosmodis - A Cosmological Distances Program - version 1.1 by Richard Powell - http://www.atlasoftheuniverse.com/ This is a simple piece of code to provide comoving, angular diameter, luminosity, and light travel distances for any given redshift. The Hubble constant (H0), Omega_matter (OM) and Omega_lambda (OL) are defined within the body of the program and can be adjusted to your favourite values. For a summary of the formulae used in this program, see: David Hogg, Distance Measures in Cosmology, (2000), astro-ph/9905116. http://arxiv.org/abs/astro-ph/9905116 The standard command for compiling this program in Linux is: cc cosmodis.c -lm -ocosmodis This program is in the Public Domain. There is no copyright. */ #include #include #define c 299792.458 int main() { float H0 = 70;// Hubble constant (km/s/Mpc) - adjust according to taste float OM = 0.27; // Omega(matter) - adjust according to taste float OL = 0.73; // Omega(lambda) - adjust according to taste float OR = 0.42/(H0*H0); // Omega(radiation) - this is the usual textbook value long i; long n=1; // Number of steps in the integral float OK = 1-OM-OR-OL;// Omega(k) defined as 1-OM-OR-OL float HD = 3.2616*c/H0/1000; // Hubble distance (billions of light years). See section 2 of Hogg float z, a, adot; // Redshift "z", Scale Factor "a", and its derivative "adot" float DC, DCC=0, DT, DTT=0, DA, DL, DM; float age, size; // The age and size of the universe printf("Enter Redshift: "); // Ask for a redshift z scanf("%f",&z); for(i=n; i>=1; i--) { // This loop is the numerical integration a = (i-0.5)/n; // Steadily decrease the scale factor
Re: [Tutor] ctypes question
Hi Joel, I found this on stackoverflow*) os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH'] windll.LoadLibrary('mydll.dll') It extends the directory list of the environment variable 'path'. Now at least I've loaded the dll, but I still need to read up on ctypes an file handles. Any good pointers (no pun intended ;-) are welcome! *) http://stackoverflow.com/questions/2980479/python-ctypes-loading-dll-from-from-a-relative-path Cheers!! Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ From: Joel Goldstick To: tutor@python.org Sent: Tue, March 8, 2011 12:14:45 PM Subject: Re: [Tutor] ctypes question On Tue, Mar 8, 2011 at 4:09 AM, ALAN GAULD wrote: > When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? >> That's consistent with os.getcwd()) > >History. >They are Unix commands (and possibly Multics/PDP before that!). >cd has been the command in almost every CLI OS I've ever used from >CP/M thru' OS/9, Unix, DOS, etc... > >The only exceptions being VAX/VMS(uses 'set def') and OS/390 on >a mainframe which doesn't use a directory based file system. > >That doesn't mean Python shouldn't adopt a more consistent naming >scheme it's just that the folks building it simply transferred the names >of the commands that they were familiar with. Its a self perpetuating >habit... :-) > >Alan G. > >___ >Tutor maillist - Tutor@python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > I'm glad to see you got the result you wanted. But, by moving your current working directory to the library's directory seems like it could cause other problems with the code. I don't do python on windows, and have unremembered a lot I used to know about windows. So, my question is, isn't there another way to do this? -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ctypes question
On Tue, Mar 8, 2011 at 4:09 AM, ALAN GAULD wrote: > > When I use os.chdir (by the way: why on earth isn't this called > os.setcwd()?? > > That's consistent with os.getcwd()) > > History. > They are Unix commands (and possibly Multics/PDP before that!). > cd has been the command in almost every CLI OS I've ever used from > CP/M thru' OS/9, Unix, DOS, etc... > > The only exceptions being VAX/VMS(uses 'set def') and OS/390 on > a mainframe which doesn't use a directory based file system. > > That doesn't mean Python shouldn't adopt a more consistent naming > scheme it's just that the folks building it simply transferred the names > of the commands that they were familiar with. Its a self perpetuating > habit... :-) > > Alan G. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I'm glad to see you got the result you wanted. But, by moving your current working directory to the library's directory seems like it could cause other problems with the code. I don't do python on windows, and have unremembered a lot I used to know about windows. So, my question is, isn't there another way to do this? -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] binary string parsing
Hi I am receiving a string over a socket connection. The string may be either line and value delimited ascii, or formated binary. The skeleton of the code which handles the data is: buffer = socket.recv(1000) lines = buffer.split(linedelim) for line in lines: if datatype == 'binary': if len(line) == binaryrecordsize: values = unpack(formatin,line) else: print('error') else: values = line.split(signaldelim) My problem arises when handling data which may be either big or little endian. The endianess is handled properly when unpacking each line of data from the buffer but I was not sure how to handle the process if splitting the buffer into individual lines using the line delimiter. The problem was first encountered when unpacking a formated binary buffer which had \xBA\xBA as the line delimiter. The above code worked fine most of the time but occasionally an \xBA would crop up as the last byte of the line becasue the byte order was different than the default assumed for the buffer. Thanks Robert Clement -- 202 Crew Building West Mains Road Edinburgh UK, EH9 3JN phone +44 131 650 7732 The University of Edinburgh is a charitable body, registered in Scotland, with registration number SC005336. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] BLAS Implementation on Python
Alan Gauld, 08.03.2011 09:51: "Knacktus" wrote He doesn't have to write it, as it is very obvious, that no Python code on earth (even written by Guido himself ;-)) stands a chance compared to Fortran or C. Look at this: There is one big proviso. The C or Fortran needs to be well written in the first place. It's quite possible to write code in Python that outperforms badly written C. And it is quite easy to write bad C! It's seriously hard to write computational Python code that is faster than C code, though. It shifts a bit if you can take advantage of Python's dynamic container types, especially dicts, but that's rarely the case for mathematic computation code, which would usually deploy NumPy etc. in Python. Writing that in pure Python is bound to be incredibly slow, and likely still several hundred times slower than even a simple approach in C. There's a reason people use NumPy, C, Fortran and Cython for these things. Remember that the OP's topic was a BLAS implementation. The BLAS libraries are incredibly well optimised for all sorts of platforms, including GPUs. They are building blocks that C programmers can basically just plug into their code to run hugely fast computations. There is no way Python code will ever be able to get any close to that. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ctypes question
> When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? > That's consistent with os.getcwd()) History. They are Unix commands (and possibly Multics/PDP before that!). cd has been the command in almost every CLI OS I've ever used from CP/M thru' OS/9, Unix, DOS, etc... The only exceptions being VAX/VMS(uses 'set def') and OS/390 on a mainframe which doesn't use a directory based file system. That doesn't mean Python shouldn't adopt a more consistent naming scheme it's just that the folks building it simply transferred the names of the commands that they were familiar with. Its a self perpetuating habit... :-) Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ctypes question
Hi all, Thanks for your replies. It wasn't a permissions issue. Apparently, not the full path name should be used. When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? That's consistent with os.getcwd()) and then use the file name only, it works. See the Idle session below. Thought it'd be nice to share this with you. Best wishes, Albert-Jan Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2.4 >>> import ctypes >>> lib = ctypes.cdll.LoadLibrary("d:/temp/spss_io/win32/spssio32.dll") Traceback (most recent call last): File "", line 1, in lib = ctypes.cdll.LoadLibrary("d:/temp/spss_io/win32/spssio32.dll") File "C:\Python25\lib\ctypes\__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] Kan opgegeven module niet vinden >>> import os >>> os.path.exists("d:/temp/spss_io/win32/spssio32.dll") True >>> os.chdir("d:/temp/spss_io/win32") >>> lib = ctypes.cdll.LoadLibrary("spssio32.dll") >>> dir(lib) ['_FuncPtr', '__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_handle', '_name'] >>> Cheers!! Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ From: Alan Gauld To: tutor@python.org Sent: Mon, March 7, 2011 7:26:15 PM Subject: Re: [Tutor] ctypes question "Pacific Morrowind" wrote > but that path doesn't actually exist... replace that path with either > r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise the > /t will be transformed into a tab. You've got your / and \ mixed up. Forward slashes (/) are fine in Windows paths. It's back slashes(\) that need escaping or raw stringing. \t is tab... On the original ask - could it be a permissions issue? Does your app have acess to the file? Alan G. ___ 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] BLAS Implementation on Python
"Knacktus" wrote He doesn't have to write it, as it is very obvious, that no Python code on earth (even written by Guido himself ;-)) stands a chance compared to Fortran or C. Look at this: There is one big proviso. The C or Fortran needs to be well written in the first place. It's quite possible to write code in Python that outperforms badly written C. And it is quite easy to write bad C! This is similar to the arguments in the 1960's/70's when languages like C first appeared. The assembler programmers all said you'd never replace assembler with C because assembler was an order of magnitude faster (and smaller because size mattered then!). But that was only true of well optimised assembler. Nowadays speed is hardly ever used as a reason for using assembler. Now the case between interpreted and compiled languages is slightly different, but as python compilers emerge the gap will continue to narrow. Will Python ever challenge C/assembler? Probably not in the low level domain but where we are talking about implementing complex algorithms it may well do. But its a long way off just now and if you need speed selectively rewriting in C is still the best bet. The skill is in selecting the bits to optimise. But a pure Python implementation will benefit from any improvements that are made going forward without significant rework. HTH, -- Alan Gauld 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] Expanding a variable with subprocess on Windows
Thanks, Sander. That was simple enough, as I'm learning I sometimes get caught up in these all too silly mistakes. Becky On Mon, Mar 7, 2011 at 11:38 PM, Sander Sweers wrote: > On Tue, 8 Mar 2011, 07:44:31 CET, Becky Mcquilling < > ladymcse2...@gmail.com> wrote: > > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > > > > subprocess.Popen('gpg', shell=True) > > > > It fails to run gpg and is not expanding the variable. Is there a way > > to do this that I'm missing? > > What you are doing is running Popen with a string 'gpg' instead of the > variable gpg. The below should do the trick. > > subprocess.Popen(gpg, shell=True) # notice no single quotes > > Also you usually do not need a shell and I expect your use case runs fine > without it. > > Greets > sander > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor