[PYTHON] Center difference and forward difference

When differentiating by programming, the central difference is preferable to the forward difference. The reason is that the central difference has less error.

import numpy as np

#Forward difference
def numerical_diff_forward(f,x):
  h = 1e-4
  return (f(x+h) - f(x)) / h
#Central difference
def numerical_diff_center(f,x):
  h = 1e-4
  return (f(x+h) - f(x-h)) / (h*2)


np.float32(1e-3)

def function(x):
  return 0.01*x**2+0.1*x

print(abs(0.2 - numerical_diff_forward(function,5)))
print(abs(0.2 - numerical_diff_center(function,5)))

#9.999991725240243e-07
#9.102163467389346e-13

reference [Deep Learning from scratch-the theory and implementation of deep learning learned in Python]

Recommended Posts

Center difference and forward difference
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between regression and classification
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between SQLAlchemy filter () and filter_by ()
Difference between == and is in python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between sort and sorted (memorial)
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Difference between SQLAlchemy flush () and commit ()
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
[Xg boost] Difference between softmax and softprob
difference between statements (statements) and expressions (expressions) in Python
[Django ORM] Difference between values () and only ()
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
[Python] Difference between class method and static method
Difference between docker-compose env_file and .env file
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
speed difference between wsgi, Bottle and Flask
Difference between numpy.ndarray and list (dimension, size)
Difference between ls -l and cat command
Difference and compatibility verification between keras and tf.keras # 1