lessthanoptimal / ddogleg

Java numerics library for optimization, polynomial root finding, sorting, robust model fitting, and more.
http://ddogleg.org
50 stars 18 forks source link

org.ddogleg.util.PrimitiveArrays:max method return error value for Integer(int,long) #19

Closed the-widmore closed 1 year ago

the-widmore commented 3 years ago

When input array all value is MIN_VALUE,the max method return error value.

see the test

    @Test
    public void test_long_max() {
        long[] values = {Long.MIN_VALUE, Long.MIN_VALUE};
        long max = PrimitiveArrays.max(values, 0, values.length);

        System.out.println(max == Long.MIN_VALUE);
    }

The test output false.

But, the max overloading method for byte/short array is right.

By the way,i think primitive array like min/max operate shouldn't converter the return type,even execute as int.


Suggest,use pseudo code:

  public static $type max($type[] array, int offset, int length) {
    if (array == null || array.length == 0) {
        throw new IllegalArgumentException();
    }

    $type max = array[offset];
    for (int i = 1; i < length; i++) {
        $type tmp = array[offset+i];
        if( tmp > max ) {
            max = tmp;
        }
    }
    return max;
  }

Can be easy replace.

Because the code style and compatibility,i write a issure not a pull requests.

lessthanoptimal commented 3 years ago

Thanks! Pushed the fix into SNAPSHOT already [1]. Can you double check the fixes? Old + new tests pass.

https://github.com/lessthanoptimal/ddogleg/commit/7b43d47eb5170ecea4f14e34c5c46d139551ed0b

As for returning integers instead of all int types (except long), that was done because Java stores all integers as int's unless its in an array. Using 'int' as a common type made writing data type agnostic code in another project much easier. Although, in general I prefer stronger typing.

[1] That was an accident. I need to protect that branch in this repo and force PRs!