Skip to content

Changed math functions to numpy version to allow function vectorization - #11

Open
belzebuu wants to merge 1 commit into
nathanrooy:masterfrom
belzebuu:master
Open

belzebuu wants to merge 1 commit into
nathanrooy:masterfrom
belzebuu:master

Conversation

@belzebuu

@belzebuu belzebuu commented Mar 8, 2026

Copy link
Copy Markdown

I encountered errors (TypeError: only 0-dimensional arrays can be converted to Python scalars) with vectorized use of the single valued functions, that is, when instead of passing a single number (scalar) as argument, the user gives an array of numbers. In fact, the functions expect an array of values already but in this case the vectorized form has as input a two dimensional array. An example of use that returns the error is passing the matrices from numpy.meshgrid to make 3D plots of the Ackley function.

import numpy as np
from landscapes.single_objective import rosenbrock, booth, ackley

func = ackley

x = np.linspace(-5, 5, 400)
y = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x, y)
Z = func(np.array([X, Y]))

The reason for this issue seems to be that functions from Python's standard math library (like exp, sqrt, cos), which landscapes uses, are not designed to work on arrays; they only operate on single, scalar values. When we pass the X and Y matrices from meshgrid to the function, we are trying to apply these scalar functions to entire arrays, which causes the TypeError. The solution is to use the equivalent functions from the NumPy library (np.exp, np.sqrt, np.cos), which are specifically designed to operate element-wise on arrays.

Since I needed it, I made some minimal changes myself. I make them available here. Of course, there can be many good reasons for not wanting the merge. Feel free to reject it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant