Search code examples
pythonnumpypixeltaylor-series

implementation of using Maclaurin series of e^x in python


I have numpy array and I want to use power series like taylor series of e^x, and I am wondering how to implement this in python. For the simplicity purpose, I think I can use maclaurin series at x0=0, wheres x is numpy array. Basically, I have 1 dim pixel vector, and I want to non-linearly expand each pixel value by using taylor series expansion of e^x. In other words, in output vector, each pixel will be replaced with first and second term of taylor series expansion term. Any idea to make this happen in python?

mathematical concept:

here is the simple math concept I want to accomplish, wheres nunmpy array is expected to be non-linearly expanded by using power series like maclaurin series of e^x.

enter image description here

my attempt:

import numpy as np

arr= np.array([[120.0,24.0,12.0],[14.0,28.0,43.0]])
arr= arr/255.0

def maclurin_exp(x, power):
    res = x*0
    for i in range(power):
      res += x**i/math.factorial(i)
    return res

## test my code:
maclurin_exp(x=arr, power=3)

new update 2:

Precisely, F is taylor series of e^x, x is each pixel value, x0 is approximation point at 0. For example if we have 8 pixel in 1 dim vector, then after we used taylor series of e^x for each pixel value, first and second term of taylor expansion will be considered as ouput.

enter image description here

how do I make this happen in python? any workaround to accomplish the implementation of Maclaurin series for e^x in more compact way? any thought?

expected output

for example we have 1 dim pixel vector [1,2,3,4,5,6,7,8], then we apply above mathematical equation to approximate each pixel value by using maclurin series of e^x:

pixel = [1,2,3,4,5,6,7,8]

then first and second term of taylor series of e^x for each pixel value would be my final output.


Solution

  • By the updated definition, it could be something like this:

    def exp_taylor(x, x0=0, n_terms=2):
        f_a = np.exp(x0)
        terms = [f_a * ((x-x0)**i)/np.math.factorial(i) for i in range(n_terms)]
        return np.dstack(terms).ravel()
    

    Following the fact that the expansion of e^(x) around a is e^(a) + e^(a)(x-a) + e^(a)(x-a)^2/2! and so on. The combination of dstack and ravel then interleaves the terms into a single vector. So if you have [np.array([a0,b0,c0]), np.array([a1,b1,c1])], it'll combine them to np.array([a0,a1,b0,b1,c0,c1]).

    x = np.array([1, 1, 2, 3, 5, 8, 13, 21])
    x_ = exp_taylor(x, x0=1, n_terms=3)
    print(x_)
    >>>
    [  2.71828183   0.           0.           2.71828183   0.
       0.           2.71828183   2.71828183   1.35914091   2.71828183
       5.43656366   5.43656366   2.71828183  10.87312731  21.74625463
       2.71828183  19.0279728   66.5979048    2.71828183  32.61938194
     195.71629165   2.71828183  54.36563657 543.65636569]