Hi all

I've (at least) two ways of plotting a function.

The first one is the classic :

f=(x**2).function(x)
Q=plot(f,x,-1,1)

I've an other one :

==================================
class CallFunction(object):
    def __init__(self,f):
        self.f=f
    def __call__(self,x):
        return self.f(x)

P=plot(CallFunction(f),x,-1,1)
=================================

The latter has the advantage to accept any "function" in the sense of anything that takes a x and return a number.

My question in the following : is it normal that the second one is *much* slower than the first one ?

In the following real live example, the second method takes several minutes against a couple of seconds for the first :

#! /usr/bin/sage -python
# -*- coding: utf8 -*-

from sage.all import *
from scipy import stats

class Density(object):
    def __init__(self,law,K,h,Npoints=300):
        self.Npoints=Npoints
        X=law.rvs(size=self.Npoints)
        self.N=Npoints
        self.hn=h(self.Npoints)
        self.K=K
        self.X=X
    def __call__(self,x):
return (1/(self.Npoints*self.hn))*sum( [self.K((Xi-x)/self.hn ) for Xi in self.X ] )

def fast_density(law,K,h,Npoints=300):
    hn=h(Npoints)
    X=law.rvs(size=Npoints)
    f = (1/(Npoints*hn))*sum( [   K(  (Xi-x)/hn ) for Xi in X ] )
    return f.function(x)

var('n')
K1=((1/sqrt(2*pi))*exp(-x**2/2)).function(x)
h=(n**(-0.2)).function(n)
law=stats.norm

a=-5
b=5
f=fast_density(law,K1,h)
P=plot(f,x,a,b) # couple of seconds

print "P is done ..."

g=Density(law,K1,h)
Q=plot(g,x,a,b)         # Minutes !
print "Q is done ...


For the record, the plotted functions is an approximation of the density function of a sequence of points.


Of course, in that precise example, I don't need the __call__() technique because everything is "function". In my "even more real live", however the function K is not analytic and has to be created by
def K(x):
  ... blabla

The difference between the two techniques are some hundreds of calls to Density.__call__(x) instead of f(x)


Any idea how to make the computation faster ?

Thanks
Laurent

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

Reply via email to