Skip to content

Conversation

@shivasankarka
Copy link
Collaborator

Error description

fn main() raises:
    var list: List[Scalar[nm.f64]] = List[Scalar[nm.f64]]()
    for i in range(200):
        list.append(Scalar[nm.f64](1e-5))

    var array = nm.array[nm.f64](list).reshape(nm.Shape(200, 1))
    var den = nm.exp(-array) + 1.0
    var result = Scalar[nm.f64](1.0) / (den)
    print("r: ", r)

The above code produces an array filled with 2.0 which is wrong since the expected result is an array filled with 0.5. This error occurred due to the symmetric implementation of all arithmetic operators i.e array +-*/ scalar, but this results in wrong value for division since it always calculates array / scalar even when the user input is (scalar / array).

Solution

This PR fixes this error by adding a new function to the backends that calculate the array and scalar arithmetic operations so that array / scalar and scalar / array result in the correct values.

@shivasankarka shivasankarka changed the base branch from main to pre-0.7 May 5, 2025 08:26
@shivasankarka shivasankarka changed the title [core][math] Fix error in Division of Array and a Scalar [fix][math] Fix error in Division of Array and a Scalar May 5, 2025
@shivasankarka shivasankarka requested review from MadAlex1997 and forfudan and removed request for forfudan May 5, 2025 08:30
Copy link
Collaborator

@forfudan forfudan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I somehow got confused about the backends and how arithmetic operations are finally down to the backend functions in _math_funcs.mojo. Perhaps we need to write a small API guidance for this part.

@shivasankarka
Copy link
Collaborator Author

@forfudan you are right, I also kinda got confused when I was fixing this.

@forfudan forfudan merged commit f80cc95 into Mojo-Numerics-and-Algorithms-group:pre-0.7 May 7, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants