Can't chop using SymPy in Julia

I’m using SymPy in Julia and can’t use the chop function. As a result of my calculations I have a number like

20.663702825333246 + 2.6469779601696886e-23im

If I try to:


I get this error:

MethodError: no method matching chop(::Complex{Float64})
Closest candidates are:
chop(::AbstractString) at strings/util.jl:39

Why isn’t it working, and how should I do it? (I’m working on Julia v0.5)

What do you want to do, i.e. what should chop do?

As you can read from the error message, chop works for strings, not numbers. Is round what you are looking for?

julia> round(20.663702825333246 + 2.6469779601696886e-23im, 10)
20.6637028253 + 0.0im

From the manual:

round(x, digits) rounds to the specified number of digits after the decimal place (or before if negative).
1 Like

But round isn’t defined properly for Sym Objects … Not sure what the OP wants, but perhaps round(N(x)) or x[:round]() until this is addressed.

In SymPy chop: “Chops off small real or imaginary parts, or converts numbers close to zero to exact zeros.” ( round kinda does the thing, that I want, if we don’t find better solution, I will go with that.

It isn’t pretty, and I doubt it should be nicer, but you can try SymPy.mpmath[:chop](x,tol=1e9), say

It is unclear why you need a symbolic library, but if I understand you requirements correctly, it should be easy to implement in Julia:

numchop{T <: Real}(x::T, δ = eps(T)) = abs(x) > δ ? x : zero(T)

function numchop{T <: Real}(x::Complex{T}, δ = eps(T))
    ichop = numchop(imag(x), δ)
    rchop = numchop(real(x), δ)
    if ichop == zero(T)
        complex(rchop, ichop)

Note that of course it is not type stable.

1 Like

The SymPy.mpmath[:chop](x,tol=1e9) doesn’t work, it returns a Complex{BigFloat} with a bunch of zeros at the end of both the real and imaginary parts. But the numchop function works well, thank you for your help!

This is pretty late, but one of the first modules I wrote is ZChop.jl I think it does what you want. It is similar to Mathematica’s Chop.


Try explicity wrapping the complex number with PyObject, as so PyObject(1 + 1 im) before calling the python function.