6
\$\begingroup\$

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
asked May 1, 2017 at 21:40
\$\endgroup\$
2
  • \$\begingroup\$ Doesn't this code return for any value within a which doesn't change the output from the other function? \$\endgroup\$ Commented May 1, 2017 at 22:29
  • \$\begingroup\$ And your loop doesn't change a, it loops on values of a. So is your description correct? \$\endgroup\$ Commented May 1, 2017 at 22:30

1 Answer 1

8
\$\begingroup\$
  • 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

answered May 1, 2017 at 23:44
\$\endgroup\$
1
  • \$\begingroup\$ Now the question is how to do the arange thing more efficiently. For larger range with finer accuracy, the amount of required memory is quite high (800kB for range 100, 0, -0.001 with dtype of np.float64, which is the default). Loop with manual decrement by 0.001 would introduce errors, whereas a scaled loop would require division. \$\endgroup\$ Commented May 2, 2017 at 11:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.