Ask Your Question
0

How to make Taylor expansion with fixed numerical precision?

asked 2019-12-25 05:37:23 +0100

John Bao gravatar image

updated 2019-12-25 05:40:29 +0100

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?

Thanks for your help.

edit retag flag offensive close merge delete

Comments

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)

Nasser gravatar imageNasser ( 2019-12-25 06:42:47 +0100 )edit

Thanks @Nasser. What I need is a numerical solution.

John Bao gravatar imageJohn Bao ( 2019-12-25 06:48:36 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2019-12-25 22:35:40 +0100

dsejas gravatar image

updated 2019-12-25 23:08:34 +0100

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[0] * N(ex[1], digits)
        else:
            pol += N(op, digits)
    return pol

I hope this helps!

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2019-12-25 05:37:23 +0100

Seen: 342 times

Last updated: Dec 25 '19