TransWikia.com

Shortest Floor Function

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 so answers will be scored in bytes with less bytes being a better score.

42 Answers

MMIX, 8 bytes (2 instrs)

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

Hexagony, 31 bytes

,{.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

Vyxal, 3 bytes

1%-

Push input, modulo with 1 and negate!

Try it!

Vyxal, 1 byte

Though a builtin.....

Try it!

Answered by wasif on October 27, 2021

Pyth, 3 bytes

/Q1

Try it online!

Answered by Scott on October 27, 2021

Lua, 27 25 18 15 bytes

print(...//1|0)

Try it online!

Explanation

... 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

x86-64 machine code, 7 bytes

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

Try it online!

Accepts a double in an xmm0.

Returns the floored double in xmm0.

Outgolfs the previous answer without cheesing with fixed point.

  • Nowhere did it say the return type had to be an 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.
  • This one only requires SSE4.1. ?

Yes, I know the SSE conversion functions are a little redundant in the test code.

x86-64 machine code, fixed point joke, 1 byte

Machine code:

00000000: c3                                               .

Assembly:

        .intel_syntax noprefix
        .globl floor_fixed
floor_fixed:
        ret

Try it online!

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

C (gcc), 16 15 bytes

g;f(d){g=d>>9;}

Try it online!

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

C, 42 41 bytes

int F(float x){int i=x;return i<=x?i:i-1;}

Try it online!

int F(float x){int i=x;return x>i?i:i-1;}

Try it online!

Answered by elechris on October 27, 2021

Python 3, 15 bytes

f=lambda n:n//1

Try it online!

Answered by ce_phox on October 27, 2021

Jelly, 1 byte

Try it online!

or a non-builtin answer

%1_@

Try it online!

How the second one works

%1_@ - Main link. Takes n on the left
%1   - Fractional part of n
  _@ - n - frac(n)

Answered by caird coinheringaahing on October 27, 2021

Excel, 7

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

05AB1E, 2 bytes

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

Turing Machine Code, 39 bytes

0 * * r 0
0 _ _ l 1
1 * _ l 1
1 . _ l 2

Try it online!

Answered by ouflak on October 27, 2021

Javascript - 6 bytes

Usage of the arrow function declaration (as an anonymous function here) and a bitwise "AND" operator

x=>x&x

Try it online!

or alternatively using the bitwise "OR" operator:

x=>x|0

Try it online!

Answered by Maciej Siedlecki on October 27, 2021

Julia, 17 bytes

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

Keg, 6 5 4 bytes

:1%-

Try it online!

Look ma, no unicode!

A port of the RProgN2 answer

Answered by lyxal on October 27, 2021

Wren, 16 bytes

Exactly ported from the PARI/GP answer.

Fn.new{|x|x-x%1}

Try it online!

Wren, 26 bytes

Ported from the Keg answer.

Fn.new{|x|x.split(".")[0]}

Try it online!

Answered by user85052 on October 27, 2021

AArch64 machine language (Linux), 8 bytes

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

RProgN, 1 byte

_

A builtin, thanks to the new challenge spec.

Try it online!

Answered by ATaco on October 27, 2021

x86_64 machine language (Linux), 11 bytes

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

RProgN 2, 4 bytes

]1%-

Explained

]1%-
]   # Duplicate the implicit input
 1% # Modulo 1
   -# Subtract Modulo 1 of the input from the input, inplicitly outputting the floor'd result.

Try it online!

Answered by ATaco on October 27, 2021

Java 8, 19 bytes

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)

Try It Online

Answered by Jakob on October 27, 2021

APL, 1 byte (SBCS)

According to the updated rules, built-ins are allowed:

APL (dzaima/APL), 5 4 bytes

Anonymous tacit prefix function abiding by the old prohibition on built-ins:

⊢-1|

Try it online!

 the argument

- minus

1| the division remainder when divided by 1

Answered by Adám on October 27, 2021

Perl 5, 22 bytes

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

Mouse-2002, 13 bytes

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

MATL, 5 bytes

The programming language used in this answer was created after the challenge was posted.

it1-

Examples

>> matl it1-
> 5.6
5

>> matl it1-
> -5.2
-6

Explanation

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

Python, 13

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

TI-Basic, 4 bytes

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

J 7 chars

f=:-1&|  NB. x - (x mod 1)

eg.

f 3.14
3
f _3.14
_4

Answered by Eelvex on October 27, 2021

Python (20)

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

C (80)

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

Perl (23)

$_=int($_)-(int($_)>$_)

Example:

perl -ple '$_=int($_)-(int($_)>$_)'

Every value entered on input will now be printed "floored".

Its bass5098's technique, but smaller =).

As a function(36):

sub f{int($_[0])-(int($_[0])>$_[0])}

Answered by Kent Fredric on October 27, 2021

Python (81)

def f(x):return str(x - float("." + str(float(x)).split('.')[-1])).split('.')[0]

Answered by l0nwlf on October 27, 2021

C 126 (including NL)

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

JavaScript, 50 34 33 32 characters

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

DC (15 bytes)

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

PHP, 51 45 43 37 characters

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

LISP (26)

(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

C (51)

int F(float x){int i=x-2;while(++i<=x-1);return i;}

Answered by Eelvex on October 27, 2021

PARI/GP (10)

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP