```python
from sympy import *
init_printing()
import numpy as np
from collections import OrderedDict
import matplotlib.pyplot as plt
%matplotlib inline
```

## Generic fit for approximating with a polynomial


```python
f = Symbol('f')  # Function to approximate
f_approx = Symbol('fbar')   # Approximating function
w = Symbol('w') # weighting function
chi2 = Symbol('chi^2')

f, f_approx, w, chi2
```


```python
M = Symbol('M', integer=True)
k = Symbol('k', integer=True,positive=True)
a = IndexedBase('a',(M,))  # coefficient
h = IndexedBase('h',(M,))  # basis function
ak = Symbol('a_k')  # Temporary symbols to make some derivatives easier
hk = Symbol('h_k')  #    Basis function (function of r)
hj = Symbol('h_j')
r = Symbol('r',positive=True)
j = Symbol('j',integer=True)
poly_approx = Sum(a[k]*h[k],(k,0,M))
poly_approx_j = Sum(a[j]*h[j],(j,0,M)) # replace summation variable
poly_approx
```

Define a quality-of-fit measure, $\chi^2$


```python
eq1 = Eq(chi2, Integral(w(r)*(f(r)-f_approx(r,ak))**2,r))
eq1
```

We want to minimized $\chi^2$. Take derivative wrt the coefficients ($a_k$) and set to zero.  Will get $k$ equations.


```python
eq2 = Eq(0,diff(eq1.rhs, ak))
eq2
```


```python
eq3 = Eq(diff(poly_approx,ak,evaluate=False), hk)
eq3
```


```python
eq4 = Eq(0, Integral(eq2.rhs.args[0].subs(diff(f_approx(r,ak),ak),hk(r)),r))
eq4
```


```python
eq5 = Eq(0, Integral(eq4.rhs.args[0].subs(f_approx(r,ak), poly_approx_j),r))
eq5
```


```python
eq6 = Eq(0, Integral(-eq5.rhs.args[0]/2,r))
eq6
```


```python
base7 = expand(eq6.rhs.args[0])
eq7 = Eq(Integral(-base7.args[1],r),Integral(base7.args[0],r))
eq7
```


```python
int7 = eq7.lhs.args[0]
eq8 = Eq(Sum(a[j]*Integral(Mul(*int7.args[1:]),r),(j,0,M)), eq7.rhs)
eq8
```

Finally, we get a linear system - the lhs is a matrix times a vector of coefficients and the rhs is a vector of values.


```python

```

df557ef5b7cb0a10e962aa4eafd682979fe33330
ipynb
Jupyter Notebook
LongRange/PolynomialFit.ipynb
QMCPACK/qmc_algorithms
015fd1973e94f98662149418adc6b06dcd78946d
MIT
2018-02-06T06:15:19.000Z
2019-11-26T23:54:53.000Z
LongRange/PolynomialFit.ipynb
chrinide/qmc_algorithms
015fd1973e94f98662149418adc6b06dcd78946d
MIT
2017-03-23T17:17:04.000Z
2017-03-23T17:17:04.000Z
LongRange/PolynomialFit.ipynb
chrinide/qmc_algorithms
015fd1973e94f98662149418adc6b06dcd78946d
MIT
2016-06-30T21:29:32.000Z
2019-10-22T16:10:03.000Z
Qwen/Qwen-72B
1. YES
2. YES