Monday, November 2, 2020

SciPy Highlights

 The scipy module is based on the numpy array handlers and does a variety of statistical, parameter contour space searches for minima, special treatments of sparse matrices, interpolations and hypothesis testing.


Finding roots of an equation:


from scipy.optimize import root

from math import cos

from scipy import constants


# Note that the equation can remain generalized with no definite array for x


def eqn(x):

  return x**3 + cos(x)


myroot = root(eqn, (constants.pi/2)) # pi is a best initial guess at the root


print(myroot.x)


# results in:

# the solved for root is x. nfev is the number of evaluations of the function.

fjac: array([[-1.]])

     fun: array([1.11022302e-16])

 message: 'The solution converged.'

    nfev: 16

     qtf: array([-7.64299735e-12])

       r: array([-3.00853835])

  status: 1

 success: True

       x: array([-0.86547403])



We can also evaluate for the minimum of a function:

minimize(a, b, c, d, e)


a: the objective function

b: best initial guess

c: choice of evaluation method

d: callback - optional post-iteration function to use

e: dictionary of optional parameters


def eqn(x):

  return x**2 + x - 6


themin = minimize(eqn, 10, method='BFGS')


print(themin)


# results in:


fun: -6.249999999999978

 hess_inv: array([[0.49999999]])

      jac: array([2.98023224e-07])

  message: 'Optimization terminated successfully.'

     nfev: 8

      nit: 2

     njev: 4

   status: 0

  success: True

        x: array([-0.49999985])


If we try a cubic function though, the results are not usable.


def eqn(x):

  return x**3 + x - 6


themin = minimize(eqn, 750, method='BFGS')


print(themin)


# results in:

fun: array([-6.94927495e+08])
 hess_inv: array([[-0.00037628]])
      jac: array([2353680.])
  message: 'Desired error not necessarily achieved due to precision loss.'
     nfev: 276
      nit: 18
     njev: 132
   status: 2
  success: False
        x: array([-885.75370841])


No comments:

Post a Comment