Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code a function that accepts float, list or numpy.array?

I have the following simple Python function:

def get_lerp_factor( a, x, b ):
    if x <= a: return 0.
    if x >= b: return 1.
    return (x - a) / (b - a)

Many numpy functions, like numpy.sin(x) can handle a float or an array.

So how can I extend this in the same manner, so that it can also handle a numpy array for x?

def get_lerp_factor( a, x_maybe_array, b ):
    out = (x_maybe_array - a) / (b - a) # this should work...
    # but now I have to clamp each element of out between 0 and 1

Would I have to specifically check the type of x, and branch accordingly?

How about:

def get_lerp_factor( a, x_anything, b ):
    x = np.array( x_anything )
    out = ...(x)
    # now typecast out back into the same type as x... will this work?

?

like image 523
P i Avatar asked Feb 28 '14 12:02

P i


People also ask

How do you declare a float array in Python?

You need x = np. zeros(N) , etc.: this declares the arrays as float arrays. This is the standard way of putting zeros in an array ( np. tile() is convenient for creating a tiling with a fixed array).

Should I use list or NumPy array?

Numpy data structures perform better in: Size - Numpy data structures take up less space. Performance - they have a need for speed and are faster than lists. Functionality - SciPy and NumPy have optimized functions such as linear algebra operations built in.

Can NumPy array used as list?

We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.


1 Answers

You need numpy.asarray. This takes as its first argument:

Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

and it returns:

Array interpretation of a. No copy is performed if the input is already an ndarray.

So you can implement your function like this:

import numpy as np

def get_lerp_factor(a, x, b):
    a, x, b = np.asarray(a), np.asarray(x), np.asarray(b)
    return ((x - a) / (b - a)).clip(0, 1)

This works for scalars:

>>> get_lerp_factor(0, 9, 16)
0.5625

and also for iterables:

>>> get_lerp_factor(2, range(8), 6)
array([ 0.  ,  0.  ,  0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.  ])
like image 87
Gareth Rees Avatar answered Sep 25 '22 20:09

Gareth Rees