Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tensor round to a number of decimal places #2732

Open
wangjiawen2013 opened this issue Jan 22, 2025 · 3 comments
Open

Tensor round to a number of decimal places #2732

wangjiawen2013 opened this issue Jan 22, 2025 · 3 comments
Labels
enhancement Enhance existing features

Comments

@wangjiawen2013
Copy link
Contributor

wangjiawen2013 commented Jan 22, 2025

Hi,
We can round a float in python:

import numpy as np
arr = np.array([1.23456789, 2.3456789, 3.456789])
arr_rounded = np.round(arr, 2)  # keep two decimal, output: [1.23, 2.35, 3.46]

how to round a tensor in burn like that in python ?

@laggui
Copy link
Member

laggui commented Jan 22, 2025

We have tensor.round() but the number of decimal places to round to is not configurable.

/edit: if you want to achieve that in the meantime, you can easily do it (though with additional steps)

pub fn round<B: Backend, const D: usize>(tensor: Tensor<B, D>, decimals: u32) -> Tensor<B, D> {
    if decimals == 0 {
        tensor.round()
    } else {
        let shift = 10u32.pow(decimals);
        tensor.mul_scalar(shift).round().div_scalar(shift)
    }
}

let x = Tensor::<B, 1>::from([1.23456789, 2.3456789, 3.456789]);
rounded = round(x, 2)

@wangjiawen2013
Copy link
Contributor Author

It works! Why not adding this function to tensor.round() ?

@laggui laggui changed the title Tensor round Tensor round to a number of decimal places Jan 23, 2025
@laggui laggui added the enhancement Enhance existing features label Jan 23, 2025
@laggui
Copy link
Member

laggui commented Jan 23, 2025

This could be added to the tensor.round() as a default implementation, but as you can see it's not so difficult to achieve without 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhance existing features
Projects
None yet
Development

No branches or pull requests

2 participants