Title: argmin and argmax
Slug: argmin_and_argmax
Summary: An explanation of argmin and argmax in Python.
Date: 2016-01-23 12:00
Category: Mathematics
Tags: Basics
Authors: Chris Albon
argmin and argmax are the inputs, x's, to a function, f, that creates the smallest and largest outputs, f(x).
In [1]:
import numpy as np
import pandas as pd
np.random.seed(1)
In [2]:
# Define a function that,
def f(x):
# Outputs x multiplied by a random number drawn from a normal distribution
return x * np.random.normal(size=1)[0]
In [3]:
# Create some values of x
xs = [1,2,3,4,5,6]
In [4]:
#Define argmin that
def argmin(f, xs):
# Applies f on all the x's
data = [f(x) for x in xs]
# Finds index of the smallest output of f(x)
index_of_min = data.index(min(data))
# Returns the x that produced that output
return xs[index_of_min]
In [5]:
# Run the argmin function
argmin(f, xs)
Out[5]:
In [6]:
print('x','|', 'f(x)')
print('--------------')
for x in xs:
print(x,'|', f(x))