by cupy Python Version: v10.3.1 License: MIT
by cupy Python Version: v10.3.1 License: MIT
Support
Quality
Security
License
Reuse
kandi has reviewed cupy and discovered the below as its top functions. This is intended to give you an instant insight into cupy implemented functionality, and help decide if they suit your requirements.
NumPy & SciPy for GPU
CuPy : NumPy & SciPy for GPU
>>> import cupy as cp
>>> x = cp.arange(6).reshape(2, 3).astype('f')
>>> x
array([[ 0., 1., 2.],
[ 3., 4., 5.]], dtype=float32)
>>> x.sum(axis=1)
array([ 3., 12.], dtype=float32)
QUESTION
Python create different functions in a loop
Asked 2022-Apr-11 at 05:54suppose I need to define functions that when the input is numpy array, it returns the numpy version of the function. And when the input is a cupy array, it returns cupy version of the function.
import numpy as np
import cupy as cp
def tan(arr):
return cp.tan(arr) if arr.__class__ is cp.ndarray else np.tan(arr)
I also need to create functions such as sin, cos,tanh etc. Is there a way to create those in a loop to avoid typos, or are there better ways? Thanks!
ANSWER
Answered 2022-Apr-11 at 05:54To insert into the current module 3 functions with a loop:
from functools import partial
for fn in ('tan','sin','cos'):
globals()[fn] = partial(lambda fname, arr: getattr(cp if isinstance(arr, cp.ndarray) else np, fname)(arr), fn)
How it works.. globals()
returns a dict
where you have every function & variable in the current module. So we insert lambda functions there for each func you want to define. In the lambda function we use getattr()
to get the corresponding function from np
or cp
module and call it with arr
.
The partial()
is used to "freeze" the fname
parameter.
Not sure if this is the best way but it works..
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit