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

Does Kuroko have an equivalent to Python's round() method? #48

Open
kseistrup opened this issue Feb 24, 2024 · 2 comments
Open

Does Kuroko have an equivalent to Python's round() method? #48

kseistrup opened this issue Feb 24, 2024 · 2 comments

Comments

@kseistrup
Copy link

[ Re: commit f1d7bda ]

I cannot seem to find a way to round a float to an int (or to a float with a given number of decimals), the way Python's round() does (and I ran into #47 when I tried to write a simple method that would round to an int).

I can see "round" referenced in the syn_py_types array in rline.c (line 910), but that seems to be related to Python, and not to Kuroko.

Am I missing something obvious?

If there is currently no way to round(number, ndigits=None) in Kuroko, please let this issue serve as an enhancement request.

🙏

@klange
Copy link
Collaborator

klange commented Feb 24, 2024

There is currently no implementation of the builtin round function, nor is there a binding to the libm round function in the math module.

Some references for how Python does this:

  • With ndigits=None, CPython implements float.__round__ through the libm round() function, but then adjusts the results to round halfway points to even values instead of away from zero.
  • With ndigits=something, float.__round__ is implemented through string conversion.

@klange
Copy link
Collaborator

klange commented Feb 29, 2024

With the new functionality in float.__format__, you can now use it to implement decimal rounding through the f formatter. For example, to round to 5 decimal digits past the radix point, it should suffice to do float(n.__format__('.5f')). This is not dissimilar to what CPython does to implement float rounding.

To implement truncating behavior, you may pass a sufficiently large precision to __format__ to ensure all digits are represented without rounding (all floats are exactly representable in decimal, though it may take a precision of over 1000 to get all of the digits), and then cut the desired number of digits past the decimal point. Similarly for ceil behavior, you may examine all of the digits after the cut point and determine if any of them are non-zero.

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

No branches or pull requests

2 participants