```python
import numpy as np
import sympy as sp
import numpy.linalg as la
```


```python
def finite_difference_nd(f_str, s_str, xvec, h, scheme=0):
    '''
    scheme: 0 for forward, 1 for backward, 2 for central
    '''
    formula = sp.sympify(f_str)
    symbols = sp.symbols(s_str)
    result = []
    for i in range(len(xvec)):
        temp = formula # This kind of copy is enough
        temp_plus = formula
        temp_minus = formula
        for j in range(len(symbols)):
            temp = temp.subs(symbols[j], xvec[j])
            if i == j:
                temp_plus = temp_plus.subs(symbols[j], xvec[j]+h)
                temp_minus = temp_minus.subs(symbols[j], xvec[j]-h)
            else:
                temp_plus = temp_plus.subs(symbols[j], xvec[j])
                temp_minus = temp_minus.subs(symbols[j], xvec[j])
        if scheme == 0:
            result.append(float(((temp_plus-temp)/h).evalf()))
        elif scheme == 1:
            result.append(float(((temp-temp_minus)/h).evalf()))
        else:
            result.append(float(((temp_plus-temp_minus)/h/2).evalf()))
    return result
```


```python
# @Before
tol = 10**-7
```


```python
# Test case backward finite difference method
expected = np.array([1, 2.9, 2])
actual = np.array(finite_difference_nd('x*z+y**2*z+y', 'x y z', [1, 1, 1], 0.1, scheme=1))
assert la.norm(expected - actual) < tol
```


```python
# Test case forward finite difference method
expected = np.array([1, 3.1, 2])
actual = finite_difference_nd('x*y*z+y*y+z', 'x y z', [1, 1, 1], 0.1, 0)
assert la.norm(expected - actual) < tol
```


```python
# Workspace
finite_difference_nd('x*y*z**2+x+1', 'x y z', [1, 1, 1], 0.1, 1)
```




    [2.0000000000000018, 1.0000000000000009, 1.8999999999999995]




```python

```

ef0bd6b0e21a57166521fa9253f2c2ad596e8b79
ipynb
Jupyter Notebook
finite_difference_nd.ipynb
Racso-3141/uiuc-cs357-fa21-scripts
e44f0a1ea4eb657cb77253f1db464d52961bbe5e
MIT
2021-11-02T05:56:10.000Z
2022-03-03T19:25:19.000Z
finite_difference_nd.ipynb
Racso-3141/uiuc-cs357-fa21-scripts
e44f0a1ea4eb657cb77253f1db464d52961bbe5e
MIT
finite_difference_nd.ipynb
Racso-3141/uiuc-cs357-fa21-scripts
e44f0a1ea4eb657cb77253f1db464d52961bbe5e
MIT
2021-10-30T15:18:01.000Z
2021-12-10T11:26:43.000Z
Qwen/Qwen-72B
1. YES
2. YES