Dear Jeroen, Le lundi 17 octobre 2016 09:58:38 UTC+2, Jeroen Demeyer a écrit : > > On 2016-10-17 09:53, Emmanuel Charpentier wrote: > > I need to use a fast random (complex) number generatot. > > > > The following : > > > > sage: %%cython > > ....: from sage.misc.prandom import random > > ....: cpdef complex crand(double x): > > ....: return x*random()+x*1j*random() > > > > > > is about 77 times faster than its Python equivalent : > > > > sage: def prand(x): > > ....: return CDF(2*(x*(random()-0.5)+I*x*(random()-0.5))) > > > > sage: %timeit foo=crand(8) > > The slowest run took 14.72 times longer than the fastest. This could > > mean that an intermediate result is being cached. > > 1000000 loops, best of 3: 810 ns per loop > > sage: 623000.0/810.0 > > 769.135802469136 > > sage: > > > > > > No small beer... > > > > However : > > > > sage: prand(8).parent() > > Complex Double Field > > sage: crand(8).parent() > > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call > last) > > <ipython-input-112-473e92fbb9eb> in <module>() > > ----> 1 crand(Integer(8)).parent() > > > > AttributeError: 'complex' object has no attribute 'parent' > > > > Is there a way to return a CDF (or RDF) value from a Cython function ? > > 1. Exactly the same way you would do it for a Python function: CDF(x) >

## Advertising

Thanks ! Got that (partly with Cython's tutorial). It seems that I have to add "from sage.rings.complex_double import CDF" in the Cython fragment : I can't compile without a "from sage.misc.prandom import random" declaration. That seems also that I can't type my function : if I try "cpdef CDF crand..", I get an error telling me that CDF is not a type. What are the consequences ? > > 2. If you want an even faster way, you need to use ComplexDoubleElement > internals: create the object with > ComplexDoubleElement.__new__(ComplexDoubleElement) and then manually set > the _complex attribute. > Thanks ! I'll have to lookup that. But I doubt that, in this specific case, it's worth the trouble : the overhead of calling Python's random()(twice !) probably dwarfes the return element creation. Unless I'm missing something... (or unless I'm using a C random generator, whose (correct) writing is something of a black art...). Thanks again ! -- Emmanuel Charpentier -- You received this message because you are subscribed to the Google Groups "sage-support" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-support+unsubscr...@googlegroups.com. To post to this group, send email to sage-support@googlegroups.com. Visit this group at https://groups.google.com/group/sage-support. For more options, visit https://groups.google.com/d/optout.