"unable to simplify to float approximation" error in Sage on calling a function

3.6k Views Asked by At

I have following python code in Sage:

%python
import math

T = 2.0 * math.pi
a = 1.0 / 4.0

def SumT(t, n):
    global T
    global a

    sum = 0

    if n < 0:
        return 0
    else:
        for i in range (1, n+1):
            sum = sum + ( (1.0 / (2.0 * i - 1.0)) * math.sin((2.0 * (2.0 * i - 1.0) * math.pi * t) / T) )
        return (4.0 / math.pi) * sum

t = var('t')
p = plot(SumT(t, 1), (t, 0, 1))
show(p)

Calling a function plot(SumT(t, 1), (t, 0, 1)) gives following error:

unable to simplify to float approximation

I've already looked for same problems in other threads and posts: seems that this error should be fixed with formula simplification, but I don't know how to simplify it.

The formula itself:

$$ \begin{eqnarray*}S(t;n) & = & \frac{4}{\pi}\sum_{i=1}^{n}\frac{1}{2i-1}\sin\frac{2(2i-1)\pi t}{T}\end{eqnarray*} $$

Thanks in advance!

UPDATE The problem is fixed if use pure Sage without python math import:

T = 2.0 * pi
a = 1.0 / 4.0

def SumT(t, n):
    global T
    global a

    sum = 0

    if n < 0:
        return 0
    else:
        for i in range (1, n+1):
            sum = sum + ( (1.0 / (2.0 * i - 1.0)) * sin((2.0 * (2.0 * i - 1.0) * pi * t) / T) )
        return (4.0 / pi) * sum

t = var('t')
show(plot(SumT(t, 1), (t, 0, 1)))
2

There are 2 best solutions below

0
On BEST ANSWER

The problem is fixed if use pure Sage without python math import:

T = 2.0 * pi
a = 1.0 / 4.0

def SumT(t, n):
    global T
    global a

    sum = 0

    if n < 0:
        return 0
    else:
        for i in range (1, n+1):
            sum = sum + ( (1.0 / (2.0 * i - 1.0)) * sin((2.0 * (2.0 * i - 1.0) * pi * t) / T) )
        return (4.0 / pi) * sum

t = var('t')
show(plot(SumT(t, 1), (t, 0, 1)))
3
On

The problem is with

t = var('t')

I don't know what you were getting at but t needs to be a number to produce a result.

Additionally, I had to replace pi to math.pi. And I personally wouldn't use global variables. I rewrote the code (I think your calculation is correct though!):

%python
import math

def SumT(t, n):
    T = 2.0 * math.pi
    a = 1.0 / 4.0
    sum = 0

    if n < 0:
        return 0
    else:
        for i in range (1, n+1):
            sum = sum + ((1.0 / (2.0 * i - 1.0)) * math.sin((2.0 * (2.0 * i - 1.0) * math.pi * t) / T) )
        return (4.0 / math.pi) * sum

p = list_plot([(r,SumT(t=r, n=10).n()) for r in srange(-1, 1, 0.1, include_endpoint=True)], plotjoined=True)
show(p)