Skip to content

Np\vector::sum incorrectly returns sum of absolute values #7

@sneakyimp

Description

@sneakyimp

It appears that the vector::sum function incorrectly calls blas::asum, which I believe returns the sum of absolute values instead of simply the sum of the values in a vector.

You can see the problem demonstrated with this short script:

<?php

require_once 'vendor/autoload.php';

Np\core\blas::$ffi_blas = FFI::load(__DIR__ . '/vendor/ghostjat/np/src/core/blas.h');


$v = Np\vector::ar([1, 2, 3]);
// this correctly returns 6
var_dump($v->sum());


$v = Np\vector::ar([-1, -2, -3]);
// this INCORRECTLY returns 6
var_dump($v->sum());

I don't know if there is a BLAS or LAPACK function optimized to return the correct value, but I suggest we modify the vector.php source code to change this:

     /**
     * The sum of the vector.
     * @return float
     */
    public function sum(): float {
        return blas::asum($this);
    }

to this:

    /**
     * The sum of the elements of the vector.
     * @return float
     */
    public function sum(): float {
        $sum = 0;
        for($i=0; $i<$this->ndim; $i++) {
                $sum += $this->data[$i];
        }
        return $sum;
    }

    /**
     * The sum of the absolute values of the elements of the vector.
     * @return float
     */
    public function sumAbs(): float {
        return blas::asum($this);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions