# How to make Taylor expansion with fixed numerical precision?

Following command

f(x)=sin(x)
taylor(f,x,1.0,2)


shows result:

x |--> -0.4207354924039483*(x - 1.0)^2 + 0.5403023058681398*x + 0.30116867893975674


The precision of result has too many bits, what I want is 3 bits, such as:

x |--> -0.420*(x - 1.0)^2 + 0.540*x + 0.301


How to do it?

edit retag close merge delete

May be you could just use 1 instead of 1.0? As in taylor(f,x,1,2) this gives -1/2*(x - 1)^2*sin(1) + (x - 1)*cos(1) + sin(1)

Sort by » oldest newest most voted

Hello, @john-bao! You could change the polynomial ring of the Taylor Polynomial. For example,

f(x) = sin(x)
T(x) = taylor(f, x, 1.0, 2)
R = PolynomialRing(RealIntervalField(10), 'x')
R(T)


This will give you something like

 -0.421?*x^2 + 1.39?*x - 0.120?


The ? sign indicates you have a loss of precision. I am working with 10 bits, because 3 gives you very poor precision. If you don't like the ?s, you can change the RealIntervalField(10) with Reals(10), for example. If you want to know how many bits you need in order to have 4 digits, for example, you can use the digits_to_bits function:

from sage.arith.numerical_approx import digits_to_bits
R = PolynomialRing(RealIntervalField(digits_to_bits(4)), 'x')
R(T)


Here is an alternative approach (although a little slower). This allows you to fix the number of bits or the number of digits (I'll use digits). Define the function:

def poly_prec(p, digits=4):
pol = 0
for op in p.operands():
if not op.is_constant():
ex = op.operands()
pol += ex * N(ex, digits)
else:
pol += N(op, digits)
return pol


I hope this helps!

more