# can't round directly a sum

Hi

I'm reporting this, but I'm not sure if there is a problem or not !

var('n,N',domain='integer')
var('beta,theta',domain='real')

tbNum=[theta==pi/6,beta==pi/8,N==2]
rd=7
S=sum((-1)^n*(beta + theta)^(2*n)/factorial(2*n), n, 0, N)
show(S,"\t numerical with n():\t",S.subs(tbNum).n())
show("\t numerical first n() then round : \t",round(S.subs(tbNum).n(),rd))
show("round directly : ",round(S.subs(tbNum),rd))

edit retag close merge delete

oops I forgot to precise: Sagemath 9.2, OS=W10.

but what I'm sure anyway is that if there is a problem,this should not be the most important problem at the moment! :-)

Sort by » oldest newest most voted

Hello, @ortollj! This is not a bug. The problem with the third "show" line (the direct rounding) is that, technically speaking, S.subs(tbNum) is an expression, not a number. You can verify with show(type(S.subs(tbNum))). Mathematically, there is no difference between the expression S.subs(tbNum) and the number S.subs(tbNum).n()$\approx0.6095712$. However, from the computer point of view, they have different data-types, the former a <class 'sage.symbolic.expression.Expression'> and the latter a <class 'sage.rings.real_mpfr.RealNumber'>. The round() function can only be applied to numerical data types. Conceptually, this is equivalent to try to round a string, as in round('hello', 7), although more easily confusing.

So, the solution is to first convert S to a numerical type using the method n() (or other less elegant alternatives) and then apply round(), as you did in the first two "show" lines. Alternatively, you can do the same in one step by using the digits argument for n(), as in the following bit of code:

show("round directly : ", S.subs(tbNum).n(digits=rd))


I hope this helps!

more