Bug 12547 – floor/round/ceil that optionally return a specified integral type

Status
NEW
Severity
enhancement
Priority
P4
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-04-08T12:40:20Z
Last change time
2024-12-01T16:20:47Z
Assigned to
No Owner
Creator
bearophile_hugs
Moved to GitHub: phobos#10046 →

Comments

Comment #0 by bearophile_hugs — 2014-04-08T12:40:20Z
With a small counting I've seen that in my code I have often to cast the result of the functions floor/round/ceil to integral values, like: cast(ubyte)round(x) cast(int)floor(y) But I prefer to avoid casts in my code. So I suggest to modify them (or to add new small functions) in Phobos that accept a template argument to specify the result integer type: round!ubyte(x) floor!int(y)
Comment #1 by clugdbug — 2014-04-11T10:00:20Z
FYI: They are defined to return floating-point values because that's what the equivalent C functions do. They should not be modified. Note that if you cast them to integers, you have to worry about overflow. So that's more complicated. Note also the existence of rndint() and rndlong().
Comment #2 by bearophile_hugs — 2014-04-11T11:48:27Z
(In reply to Don from comment #1) > FYI: They are defined to return floating-point values because that's what > the equivalent C functions do. They should not be modified. Perhaps lovers of C functions can use core.stdc.math: void main() { import core.stdc.math; double x = 2.7; int y1 = cast(int)floor(x); int y2 = cast(int)ceil(x); int y3 = cast(int)round(x); } But perhaps new functions can be defined in Phobos, with a different name (possibly with a clear name). > Note that if you cast them to integers, you have to worry about overflow. So > that's more complicated. In the cases where you care about overflow can't you use to! function? void main() { import std.math, std.conv; double x = 1e100; int y1 = x.floor.to!int; } > Note also the existence of rndint() and rndlong(). I don't know where they are, sorry for my ignorance. Do you mean stuff like this? http://opensource.apple.com/source/Libm/Libm-93/ppc.subproj/rndint.c In std.math I have found this: pure nothrow @safe long rndtol(real x); Returns x rounded to a long value using the current rounding mode. If the integer value of x is greater than long.max, the result is indeterminate. But what about ints, or floor/ceil? (And usually functions with name that starts with "rnd" are for random generation). Thank you Don for your answers.
Comment #3 by bearophile_hugs — 2014-04-20T14:43:11Z
In Python 3.4 those functions return an int (but Python has multiprecision integers): from math import ceil print(type(ceil(1.5))) Output: <class 'int'>
Comment #4 by robert.schadek — 2024-12-01T16:20:47Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/phobos/issues/10046 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB