Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

running sage from a Python script

I'm using sage 5.5 on ubuntu 12.04. I'm trying to run sage via the following script

#!/usr/bin/env sage -python

import sys 
from sage.all import *

sigma = 10
z = var('z')
m0 = 128 
P = exp(-(1/2)*z**2/sigma**2)/(sqrt(2*pi)*sigma)
m = m0*exp(-(1/2)*z**2) 
mb = m0/sqrt(1+sigma**2)


f = lambda u: 1-2*(numerical_integral(u*P*m**2/(mb*(u*mb+(1-u)*m)), 0, Infinity))[0] 
print find_root(f, 0.1, 1, rtol=0.01)

I run this from the command line with

sage -python runDispK1.py

and I get the following error

Warning: invalid value encountered in absolute
Warning: invalid value encountered in absolute
Warning: invalid value encountered in absolute
Warning: invalid value encountered in absolute
Warning: invalid value encountered in absolute
Traceback (most recent call last):
  File "runDispK1.py", line 16, in <module>
    print find_root(f, 0.1, 1, rtol=0.01)                          
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/numerical/optimize.py", line 108, in find_root
    raise RuntimeError, "f appears to have no zero on the interval"
RuntimeError: f appears to have no zero on the interval

Whereas if I run the exact same code within sage, e.g. I have a file called run.sage with this text in it:

    sigma = 10
    z = var('z')
    m0 = 128 
    P = exp(-(1/2)*z**2/sigma**2)/(sqrt(2*pi)*sigma)
    m = m0*exp(-(1/2)*z**2) 
    mb = m0/sqrt(1+sigma**2)


    f = lambda u: 1-2*(numerical_integral(u*P*m**2/(mb*(u*mb+(1-u)*m)), 0, Infinity))[0] 
    print find_root(f, 0.1, 1, rtol=0.01)

then sage gives me the correct answer

sage: load("run.sage")
0.550279773862

Is there something I'm missing here? I'm new to sage and python scripting but it seems the numerical_integral function is returning nothing useful, so I are these functions created incorrectly?

Thanks