mitsuki31 / jmatrix

A lightweight Java library for basic introduction to matrix and linear algebra concepts.
https://mitsuki31.github.io/jmatrix/
Apache License 2.0
1 stars 0 forks source link

[Bug]: Bad logical expression in the `insertRow` method #110

Closed mitsuki31 closed 4 months ago

mitsuki31 commented 4 months ago

Bug description

The insertRow method within the Matrix class contains flawed logic in its row index checker, which may lead to unexpected behavior when inserting rows into the matrix.

https://github.com/mitsuki31/jmatrix/blob/ebd80dd78cc2eec1a34b2591f46c5d9ce0d5fc11/src/main/java/com/mitsuki/jmatrix/Matrix.java#L958-L963

Proposed Fix

-    } else if (row < 0 || row > mRows) {  // Check for the index is out of bounds
+    } else if (row < 0 || row >= mRows) {  // Check for the index is out of bounds

The correct logic should ensure that the given row index is strictly less than the total number of rows (mRows) in the matrix, rather than allowing it to be equal to mRows. Thus, ensures proper boundary checking and prevents potential errors related to out-of-bounds row insertion.

Operating system

Windows

How did you use the software?

Built from source

Steps to reproduce

  1. Create a new Matrix object as usual
    Matrix m = new Matrix({ { 1., 2. } });
  2. Insert a new array to specific row in the matrix using insertRow method with the row argument from the getNumRows (retrieve the total rows of the matrix, in this case 1).
    // The index count from zero and so on, here if we give the total number of rows
    // which is 1 (one), so it equals to 2 (two) because counting from zero.
    // The issue is because this method does not throws any exception.
    m = m.insertRow(m.getNumRows(), new double[] { 3. });
  3. No error get thrown both in compile time and runtime execution. Instead the method should throws a InvalidIndexException custom exception due to the given row index is out of range.

Relevant log output

No response

Code of Conduct