MCPcopy Create free account
hub / github.com/numpy/numpy / fast_scalar_power

Function fast_scalar_power

numpy/core/src/multiarray/number.c:506–577  ·  view source on GitHub ↗

* optimize float array or complex array to a scalar power * returns 0 on success, -1 if no optimization is possible * the result is in value (can be NULL if an error occurred) */

Source from the content-addressed store, hash-verified

504 * the result is in value (can be NULL if an error occurred)
505 */
506static int
507fast_scalar_power(PyObject *o1, PyObject *o2, int inplace,
508 PyObject **value)
509{
510 double exponent;
511 NPY_SCALARKIND kind; /* NPY_NOSCALAR is not scalar */
512
513 if (PyArray_Check(o1) &&
514 !PyArray_ISOBJECT((PyArrayObject *)o1) &&
515 ((kind=is_scalar_with_conversion(o2, &exponent))>0)) {
516 PyArrayObject *a1 = (PyArrayObject *)o1;
517 PyObject *fastop = NULL;
518 if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) {
519 if (exponent == 1.0) {
520 fastop = n_ops.positive;
521 }
522 else if (exponent == -1.0) {
523 fastop = n_ops.reciprocal;
524 }
525 else if (exponent == 0.0) {
526 fastop = n_ops._ones_like;
527 }
528 else if (exponent == 0.5) {
529 fastop = n_ops.sqrt;
530 }
531 else if (exponent == 2.0) {
532 fastop = n_ops.square;
533 }
534 else {
535 return -1;
536 }
537
538 if (inplace || can_elide_temp_unary(a1)) {
539 *value = PyArray_GenericInplaceUnaryFunction(a1, fastop);
540 }
541 else {
542 *value = PyArray_GenericUnaryFunction(a1, fastop);
543 }
544 return 0;
545 }
546 /* Because this is called with all arrays, we need to
547 * change the output if the kind of the scalar is different
548 * than that of the input and inplace is not on ---
549 * (thus, the input should be up-cast)
550 */
551 else if (exponent == 2.0) {
552 fastop = n_ops.square;
553 if (inplace) {
554 *value = PyArray_GenericInplaceUnaryFunction(a1, fastop);
555 }
556 else {
557 /* We only special-case the FLOAT_SCALAR and integer types */
558 if (kind == NPY_FLOAT_SCALAR && PyArray_ISINTEGER(a1)) {
559 PyArray_Descr *dtype = PyArray_DescrFromType(NPY_DOUBLE);
560 a1 = (PyArrayObject *)PyArray_CastToType(a1, dtype,
561 PyArray_ISFORTRAN(a1));
562 if (a1 != NULL) {
563 /* cast always creates a new array */

Callers 2

array_powerFunction · 0.85
array_inplace_powerFunction · 0.85

Calls 5

can_elide_temp_unaryFunction · 0.85
PyArray_CastToTypeFunction · 0.85

Tested by

no test coverage detected