def test_1(self): x = 10.0 xh = hyperdual(x, 1.0, 1.0, 0.0) for func in [func1, func2]: f = func(x) fh = func(xh)[0] self.assertEqual(f[0], fh.f0) self.assertEqual(f[1], fh.f1) self.assertEqual(f[1], fh.f2) self.assertEqual(f[2], fh.f12)
def test_2(self): x = 1.1 xh = hyperdual(x, 1.0, 1.0, 0.0) f = complex_func(x) h = 1e-6 fd_1 = (complex_func(x + h) - complex_func(x - h))/2/h fd_2 = (complex_func(x + h) - complex_func(x)*2.0 + complex_func(x - h))/h/h fh = complex_func(xh) self.assertEqual(f, fh.f0) self.assertAlmostEqual(fd_1, fh.f1,3) self.assertAlmostEqual(fd_1, fh.f2,3) self.assertAlmostEqual(fd_2, fh.f12,-1) print 'finite diff: ', fd_1, fd_2 print 'hyper dual: ', fh.f1, fh.f12
def test_2(self): x = 1.1 xh = hyperdual(x, 1.0, 1.0, 0.0) f = complex_func(x) h = 1e-6 fd_1 = (complex_func(x + h) - complex_func(x - h)) / 2 / h fd_2 = (complex_func(x + h) - complex_func(x) * 2.0 + complex_func(x - h)) / h / h fh = complex_func(xh) self.assertEqual(f, fh.f0) self.assertAlmostEqual(fd_1, fh.f1, 3) self.assertAlmostEqual(fd_1, fh.f2, 3) self.assertAlmostEqual(fd_2, fh.f12, -1) print 'finite diff: ', fd_1, fd_2 print 'hyper dual: ', fh.f1, fh.f12
import sys import unittest sys.path.append('../build/lib.linux-x86_64-2.7/hyperdual') from numpy_hyperdual import hyperdual import numpy as np from pylab import * x = np.linspace(0.0, 2*np.pi, 13) f = np.sin(x) dfdx = np.cos(x) dfdx2 = -np.sin(x) xh = np.zeros_like(x, dtype=hyperdual) for i in range(len(x)): xh[i] = hyperdual(x[i], 1.0, 1.0, 0.0) fh = np.sin(xh) fhd_0 = np.zeros_like(x) fhd_1 = np.zeros_like(x) fhd_2 = np.zeros_like(x) fhd_12 = np.zeros_like(x) for i in range(len(x)): fhd_0[i] = fh[i].f0 fhd_1[i] = fh[i].f1 fhd_2[i] = fh[i].f2 fhd_12[i] = fh[i].f12