Hacker News new | ask | show | jobs
by Jenz 2490 days ago
I dunno, how efficient is this?
3 comments

So efficient that nobody really cared about or mentioned it all those decades, so there's that...
I agree - my takeaway is "float-to-string and string-to-float conversion is probably faster than I thought"
Compared to base=10^places, multiply, truncate, divide? Horriby inefficient.
Sure, but their approach is on the other hand more correct. All numerical code reaches a point where you have to balance performance vs. correctness, and here cpython has chosen correctness over speed.
They're creating a sequence of digits and then truncating. If you want to replicate that precisely, you could use an accumulator and a loop to do the same thing. At least then you could break early.
It's slower than native python.

    %timeit round(12335423552.33, -6)
    %timeit int(12335423552.33 / 1_000_000.0) * 1_000_000.0
    500 ns ± 3.88 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    219 ns ± 1.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Well obviously the approach round() takes is slower than the naive approach. The whole point of doing it the way round() does it is that it gives the correct answer in cases where the naive approach fails.