Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Numerical Methods Homework

Views: 706
Kernel: Python 3 (Anaconda)
import scipy.optimize as optimize import numpy as np def f1a(x): return x**3-x-2 def f1b(x): return -1*np.exp(x)+7 def f1c(x): return e^x+sin(x)-4+x print('1(a) = ',optimize.fixed_point(f1a,0, xtol=1e-8)) print('1(b) = ',optimize.fixed_point(f1b,0)) print('1(c) = ',optimize.fixed_point(f1c,0)) def f2a(x): return -x**5+1 def f2b(x): return np.e**(x**2+3) def f2c(x): return np.sqrt(-np.log(x) + 3) print('2(a) = ',optimize.fixed_point(f2a,0, xtol=1e-8)) print('2(b) = ',optimize.fixed_point(f2b,0)) print('2(c) = ',optimize.fixed_point(f2c,0, maxiter=10000)) #Due to Python's precise nature, this code causes an overflow error for some choices of f(x).
1(a) = 1.7692923542386314 1(b) = 1.6728216986289064
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-1cfd69b5dec4> in <module>() 10 print('1(a) = ',optimize.fixed_point(f1a,0, xtol=1e-8)) 11 print('1(b) = ',optimize.fixed_point(f1b,0)) ---> 12 print('1(c) = ',optimize.fixed_point(f1c,0)) 13 14 def f2a(x): /ext/anaconda3/lib/python3.5/site-packages/scipy/optimize/minpack.py in fixed_point(func, x0, args, xtol, maxiter, method) 891 use_accel = {'del2': True, 'iteration': False}[method] 892 x0 = _asarray_validated(x0, as_inexact=True) --> 893 return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel) /ext/anaconda3/lib/python3.5/site-packages/scipy/optimize/minpack.py in _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel) 833 p0 = x0 834 for i in range(maxiter): --> 835 p1 = func(p0, *args) 836 if use_accel: 837 p2 = func(p1, *args) <ipython-input-2-1cfd69b5dec4> in f1c(x) 7 return -1*np.exp(x)+7 8 def f1c(x): ----> 9 return e^x+sin(x)-4+x 10 print('1(a) = ',optimize.fixed_point(f1a,0, xtol=1e-8)) 11 print('1(b) = ',optimize.fixed_point(f1b,0)) NameError: name 'e' is not defined
def sqrt(x): list = [x] last = list[-1] next = 0 while (np.abs(next-last)>.5): next = (last + x/last)/2 list.append(next) last = list[-1] print(next) sqrt(3)
def dx(f, x): return abs(0-f(x)) def newtons_method(f, df, x0, e): delta = dx(f, x0) while delta > e: x0 = x0 - f(x0)/df(x0) delta = dx(f, x0) print ('Root is at: ', x0) print ('f(x) at root is: ', f(x0)) n