HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Maximum value that satisfies a specific function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
maximumfunctionvaluethatspecificsatisfies

Problem

I want to find the maximum value for a that doesn't change the output from another function. (_find_mean simply finds the location of the maximum element in a matrix)

This is how I am currently doing it and was wondering if there was a better way.

def _find_max_a(matrix1, matrix2):
    a = np.arange(0,10, 0.01)[::-1]
    for val in a:
        mat = matrix1 +  val * matrix2
        if _find_mean(matrix1) == _find_mean(mat):
            return val
        else:
            pass

Solution

-
arange can build a descending vector. Building an ascending vector and reversing it seems wasteful. Consider

a = np.arange(10, 0, -0.01)


-
matrix1 is never modified, but its _find_mean is recomputed on each iteration. Yet another waste. Compute it once.

-
Instead of linear search, you may want to consider a bisection of the search interval.

-
else: pass achieves nothing, and can be safely omitted.

-
_find_mean is a kinda strange name for a function which


finds the location of the maximum element in a matrix

Code Snippets

a = np.arange(10, 0, -0.01)

Context

StackExchange Code Review Q#162276, answer score: 8

Revisions (0)

No revisions yet.