Code Golf Asked on October 27, 2021
Your task is to implement a floor function in as few bytes as possible.
A floor function is a function that takes a real number and returns the largest integer less than or equal to the input.
Your program should support both positive and negative inputs. Since it is provably impossible to support all real numbers you need only support a reasonable subset of them. This subset should include positive numbers, negative numbers and of course numbers that are not integers. Such number systems include fixed-point numbers, floating point numbers and strings.
Your code may be a complete program or function.
This is code-golf so answers will be scored in bytes with less bytes being a better score.
05000300 F8010000
Disassembly
FIX $0,ROUND_DOWN,$0
POP 1,0
MMIX has a builtin instruction for this. You can specify the rounding mode if you like, but you can use the default. (Options are towards 0, towards $-infty$, towards $infty$, or to nearest half to even.)
Honestly, I'd advise using a FIX
directly, as opposed to calling.
Answered by NoLongerBreathedIn on October 27, 2021
,{.4{?<.(@!?"!3'-<_".$>@>?~..@
, { . 4
{ ? < . (
@ ! ? " !
3 ' - < _ " .
$ > @ > ? ~
. . @ . .
. . . .
Try it online! or Try it online differently!
Takes input of the form +/-a.b
, ex: +4.5
or -0.1
or +3.
Since hexagony doesn't have built in decimal types, the input must contain a +
if positive in order to not cut off the first digit of the number. This answer can definitely be improved, but its a start.
Answered by Underslash on October 27, 2021
1%-
Push input, modulo with 1 and negate!
⌊
Though a builtin.....
Answered by wasif on October 27, 2021
Answered by Scott on October 27, 2021
print(...//1|0)
...
variable-argument operator, returns the remaining arguments passed to the current function (top-level code block with all the program arguments in this case).
//1
floor divides by 1.
|0
bitwise OR, we use this to convert to an int.
Answered by Benrob0329 on October 27, 2021
Machine code:
00000000: 66 0f 3a 0b c0 01 c3 f.:....
Assembly:
.intel_syntax noprefix
.globl floor_sse4
floor_sse4:
roundsd xmm0, xmm0, 1
ret
Accepts a double
in an xmm0
.
Returns the floored double
in xmm0
.
Outgolfs the previous answer without cheesing with fixed point.
int
, just an integer. Therefore, I can just skip the conversion code, storing the integer as a double
. JavaScript has been doing it for decades.Yes, I know the SSE conversion functions are a little redundant in the test code.
Machine code:
00000000: c3 .
Assembly:
.intel_syntax noprefix
.globl floor_fixed
floor_fixed:
ret
This function takes a 16-bit fixed8 in ax
and returns a signed 8-bit integer in ah
. It is not sign extended.
Nobody gave any specifics about precision ?
Answered by EasyasPi on October 27, 2021
g;f(d){g=d>>9;}
Such number systems include fixed-point numbers, floating point numbers and strings.
I don't know why people insist on using floats... Fixed point is much easier ?
Uses 32-bit fixed9 precision. Abuses arithmetic shift right. Return hack, not much else to say.
Answered by EasyasPi on October 27, 2021
int F(float x){int i=x;return i<=x?i:i-1;}
int F(float x){int i=x;return x>i?i:i-1;}
Answered by elechris on October 27, 2021
Answered by ce_phox on October 27, 2021
Ḟ
or a non-builtin answer
%1_@
%1_@ - Main link. Takes n on the left
%1 - Fractional part of n
_@ - n - frac(n)
Answered by caird coinheringaahing on October 27, 2021
Tested in Excel Online. Closing parens not counted toward score.
The only reason I posted this is because, oddly enough, it seems to work the exact same as FLOOR.MATH()
with 1 argument.
=INT(A1)
Semantically, at least to me, it would make sense if this didn't work for negative numbers. However, INT(-.5)
is -1
for some reason. TRUNC()
does what I think INT()
should do.
Answered by Calculuswhiz on October 27, 2021
Oï
Try it online or verify all values in the range $[5,-5]$ in $0.1$ increments.
Explanation:
O # Sum the stack, which will use the (implicit) input-string if the stack is empty
# (the input is read as string by default, so this `O` basically casts it to a float)
ï # Floor this input-float
# (and output the resulting integer implicitly)
Although it may look pretty straight-forward, there are actually some things to note:
In the legacy version of 05AB1E, which was built in Python. The ï
builtin would translate to the following code snippets:
# Pop number
a = str(number) # Cast number to a string
a = ast.literal_eval(a) # Evaluate this string as Python structure (so it goes back to a float)
a = int(a) # Cast this float to an integer (which will truncate)
So whether you had string input or decimal input, it would cast it to a string during the code execution anyway, before casting it to an integer to truncate all decimal values.
Try it online with -0.5
as decimal argument.
Try it online with "-0.5"
as string argument.
The new version of 05AB1E is built in Elixir however. Now, the ï
builtin translates to the following code snippets (huge parts removed to only keep the relevant stuff):
call_unary(fn x -> to_integer(x) end, a) # Call the function `to_integer`, which will:
# (I've only kept relevant parts of this function)
is_float(value) -> round(Float.floor(value)) # If it's a float: floor it down
true -> # Else (it's a string):
case Integer.parse(to_string(value)) do # Parse it from string to integer
:error -> value # If this resulted in an error: return as is
{int, string} ->
cond do # Else it was parsed without errors:
Regex.match?(~r/^.d+$/, string) -> int
# If it contains no decimal values:
# Return parsed int
true -> value # Else: return as is
Or as a TL;DR: float inputs are floored; string inputs are truncated.
Try it online with -0.5
as decimal argument.
Try it online with "-0.5"
as string argument.
As you can see, a string input gives the incorrect floored result for negative decimals. Unfortunately, the default (implicit) input from STDIN is always a string, so we'll have to convert it to a float first (for which I've used O
- which only works on an empty stack in the new 05AB1E version built in Elixir; for the legacy 05AB1E version built in Python, the sum would result in 0
for an empty stack).
Answered by Kevin Cruijssen on October 27, 2021
Answered by ouflak on October 27, 2021
Usage of the arrow function declaration (as an anonymous function here) and a bitwise "AND" operator
x=>x&x
or alternatively using the bitwise "OR" operator:
x=>x|0
Answered by Maciej Siedlecki on October 27, 2021
f(x)=x-x%1-(x<0)
port of the PARI/GP answer
f(-pi) = -4
f(pi) = 3
Answered by caseyk on October 27, 2021
Answered by lyxal on October 27, 2021
Exactly ported from the PARI/GP answer.
Fn.new{|x|x-x%1}
Ported from the Keg answer.
Fn.new{|x|x.split(".")[0]}
Answered by user85052 on October 27, 2021
0: 1e700000 fcvtms w0, d0
4: d65f03c0 ret
To try it out, compile and run the following C program
#include<stdio.h>
#include<math.h>
int f(double x){return floor(x);}
const char g[]="x00x00x70x1exc0x03x5fxd6";
int main(){
for( double d = -1.5; d < 1.5; d+=.2 ) {
printf( "%f %d %dn", d, f(d), ((int(*)(double))g)(d) );
}
}
Answered by ceilingcat on October 27, 2021
Answered by ATaco on October 27, 2021
0: c4 e3 79 0b c0 01 vroundsd $0x1,%xmm0,%xmm0,%xmm0
6: f2 0f 2c c0 cvttsd2si %xmm0,%eax
a: c3 retq
This requires a processor with AVX instructions.
To Try it online!, compile and run the following C program.
#include<stdio.h>
#include<math.h>
int f(double x){return floor(x);}
const char g[]="xc4xe3x79x0bxc0x01xf2x0fx2cxc0xc3";
int main(){
for( double d = -1.5; d < 1.5; d+=.2 ) {
printf( "%f %d %dn", d, f(d), ((int(*)(double))g)(d) );
}
}
Answered by ceilingcat on October 27, 2021
]1%-
]1%-
] # Duplicate the implicit input
1% # Modulo 1
-# Subtract Modulo 1 of the input from the input, inplicitly outputting the floor'd result.
Answered by ATaco on October 27, 2021
Lambda from double
to int
. There are plenty of choices for types to assign to: Function<Double, Integer>
, DoubleFunction<Integer>
, or DoubleToIntFunction
.
n->(int)(n<0?n-1:n)
Answered by Jakob on October 27, 2021
According to the updated rules, built-ins are allowed:
⌊
Anonymous tacit prefix function abiding by the old prohibition on built-ins:
⊢-1|
⊢
the argument
-
minus
1|
the division remainder when divided by 1
Answered by Adám on October 27, 2021
s/..+//&&$_<0?$_--:$_
This is larger than my first answer, which merely truncated the number - so, for negative numbers, it wasn't correct. This was due to a misunderstanding on my part of what a floor function does.
Answered by Codefun64 on October 27, 2021
Second place, ahh! (And this is a full program, not a function definition)
?&DUP &FRAC -
Take the fractional bit of the input and subtract it from the input.
Answered by cat on October 27, 2021
The programming language used in this answer was created after the challenge was posted.
it1-
>> matl it1-
> 5.6
5
>> matl it1-
> -5.2
-6
Pretty straightforward. It uses a modulo operation with divisor 1
.
i % input
t % duplicate
1 % number literal
% modulus after division
- % subtraction
Answered by Luis Mendo on October 27, 2021
If the OP wants all functions to be non-anonymous, add f=
to the front of each for two additional characters.
lambda x:x//1
Since x%1
returns the amount following the decimal point, this is pretty short (14):
lambda x:x-x%1
The shortest using string casting I could come up with (40):
lambda x:int(`x`.split('.')[0])+cmp(x,0)
Answered by mbomb007 on October 27, 2021
X-fPart(X
fPart(
is a one-byte token, stands for 'fractional part' and returns anything right of the decimal point. Parentheses don't need to be closed in TI-Basic.
Answered by hallo on October 27, 2021
f=:-1&| NB. x - (x mod 1)
eg.
f 3.14
3
f _3.14
_4
Answered by Eelvex on October 27, 2021
f=lambda x:int(x//1)
or, if the result doesn't need to be of type int
, 15 characters:
f=lambda x:x//1
Answered by dan04 on October 27, 2021
Ruby 1.9 (12 14)
f=->x{x-x%1}
It's more a "for the record" type solution along the lines of the PARI/GP one.
>> f[3.4] #=> 3.0
>> f[-3.4] #=> -4.0
Answered by Michael Kohl on October 27, 2021
Well it's not the shortest, but it's a great opportunity to show off my bit twiddling skills :D.
main(){int I,X=0x7FFFFF;scanf("%f",&I);printf("%d",((I&X)|X+1)>>-(I>>23)+150);}
Answered by Hannesh on October 27, 2021
$_=int($_)-(int($_)>$_)
Example:
perl -ple '$_=int($_)-(int($_)>$_)'
Every value entered on input will now be printed "floored".
Its bass5098's technique, but smaller =).
sub f{int($_[0])-(int($_[0])>$_[0])}
Answered by Kent Fredric on October 27, 2021
def f(x):return str(x - float("." + str(float(x)).split('.')[-1])).split('.')[0]
Answered by l0nwlf on October 27, 2021
Doesn't use any built-in conversion such as (int)x
.
r(float x) {
int
p=*(int*)&x,
f=p&8388607|1<<23,
e=((p>>23)&255)-150;
if(e>0)f*=1<<e;
if(e<0)f/=1<<-e;
return p>>31?-f-1:f;
}
Answered by Alexandru on October 27, 2021
function f(n){return~~n-(~~n>n)}
Works the same way as the PHP one I submitted.
Answered by Kevin Brown-Silva on October 27, 2021
Makes use of a nifty little trick that occurs during division in DC. Add a 'p' to then end to get output (it performs the floor correctly anyway), I assume that stuff is not already on the stack, and that input is in stdin.
[1-]sazk?z/d0>a
EG: echo 0 2.6 - | dc -e '[1-]sazk?z/d0>ap'
Answered by Hiato on October 27, 2021
function f($n){return~~$n-(~~$n>$n);}
This should be able to be applied to most languages that do not support the n%1
trick.
Answered by Kevin Brown-Silva on October 27, 2021
(Same trick as in PARI/GP answer)
(defun f(x)(- x(mod x 1)))
Answered by Eelvex on October 27, 2021
C# (56 chars):
My quick and naive answer earlier had a stupid logical flaw in it. Two approaches here, which I believe are both the same length. Double approach relies on the fact that casting to int removes the decimal part of a double.
int F(double d){return(int)(d%1==0?d:(int)d-(d<0?1:0));}
Decimal approach relies on the fact that d%1 returns the decimal part of the number for decimal data type.
int F(decimal d){return(int)(d%1==0?d:d-d%1-(d<0?1:0));}
Could save a few characters in both cases by returning their own type instead of int, but I feel a floor function should return an int.
Answered by Nellius on October 27, 2021
int F(float x){int i=x-2;while(++i<=x-1);return i;}
Answered by Eelvex on October 27, 2021
In gp (and some other languages) x%1 gives the decimal part of x:
f(x)=x-x%1
NOTE: For negative x, x%1 returns (1 - abs(decimal part of x)), so the above works both for positive and negative numbers.
Answered by Eelvex on October 27, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP