27
\$\begingroup\$

Challenge

Given a (floating-point/decimal) number, return its reciprocal, i.e. 1 divided by the number. The output must be a floating-point/decimal number, not just an integer.

Detailed specification

  • You must receive input in the form of a floating-point/decimal number...
    • ...which has at least 4 significant digits of precision (if needed).
    • More is better, but does not count in the score.
  • You must output, with any acceptable output method...
    • ...the reciprocal of the number.
    • This can be defined as 1/x, x⁻¹.
    • You must output with at least 4 significant digits of precision (if needed).

Input will be positive or negative, with absolute value in the range [0.0001, 9999] inclusive. You will never be given more than 4 digits past the decimal point, nor more than 4 starting from the first non-zero digit. Output needs to be accurate up to the 4th digit from the first non-zero one.

(Thanks @MartinEnder)

Here are some sample inputs:

0.5134
0.5
2
2.0
0.2
51.2
113.7
1.337
-2.533
-244.1
-0.1
-5

Note that you will never be given inputs which have above 4 digits of precision.

Here is a sample function in Ruby:

def reciprocal(i)
    return 1.0 / i
end

Rules

  • All accepted forms of output are allowed
  • Standard loopholes banned
  • This is , shortest answer in bytes wins, but will not be selected.

Clarifications

  • You will never receive the input 0.

Bounties

This challenge is obviously trivial in most languages, but it can offer a fun challenge in more esoteric and unusual languages, so some users are willing to award points for doing this in unusually difficult languages.

  • @DJMcMayhem will award a +150 points bounty to the shortest brain-flak answer, since brain-flak is notoriously difficult for floating-point numbers

  • @L3viathan will award a +150 points bounty to the shortest OIL answer. OIL has no native floating point type, nor does it have division.

  • @Riley will award a +100 points bounty to the shortest sed answer.

  • @EriktheOutgolfer will award a +100 points bounty to the shortest Sesos answer. Division in brainfuck derivatives such as Sesos is very difficult, let alone floating-point division.

  • I (@Mendeleev) will award a bounty of +100 points to the shortest Retina answer.

If there's a language you think would be fun to see an answer in, and you're willing to pay the rep, feel free to add your name into this list (sorted by bounty amount)

Leaderboard

Here is a Stack Snippet to generate an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=114544,OVERRIDE_USER=62393;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={};e.forEach(function(e){var o=e.language;/<a/.test(o)&&(o=jQuery(o).text().toLowerCase()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link,uniq:o}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.uniq>s.uniq?1:e.uniq<s.uniq?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=617d0685f6f3"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>

\$\endgroup\$
  • 23
    \$\begingroup\$ Please stop upvoting trivial answers \$\endgroup\$ – user41805 Mar 30 '17 at 18:04
  • 15
    \$\begingroup\$ @KritixiLithos People can vote as they see fit. Given the simplicity of this challenge, most, if not all answers are something like 1/x. \$\endgroup\$ – NoOneIsHere Mar 30 '17 at 18:08
  • 9
    \$\begingroup\$ This isn't objectively specified without very clear detail on accuracy and precision. \$\endgroup\$ – Peter Taylor Mar 30 '17 at 18:10
  • 6
    \$\begingroup\$ What about accuracy? Presumably you want 4 sf of accuracy too, but then there's the issue of rounding. Floating point questions are hard to get right and very worth sandboxing. \$\endgroup\$ – Peter Taylor Mar 30 '17 at 20:27
  • 10
    \$\begingroup\$ -1, this is a poor challenge because using a builtin is the ONLY way to do it and know you have satisfied the "specification". If you have a standard floating point implementation, you can use it and tell yourself this is standard floating point, it must be ok. If you have to implement it yourself, there is no specification so you can't sensibly try to golf it. \$\endgroup\$ – feersum Mar 31 '17 at 5:12

90 Answers 90

3
\$\begingroup\$

Perl 6, 3 bytes

1/*

Try it

This also works, but is 5 or 6 bytes
You can use (superscript minus) at 3 bytes, or ¯ (macron) which is 2 bytes

*⁻¹

Try it

|improve this answer|||||
\$\endgroup\$
3
\$\begingroup\$

C++ lambda function, 24 bytes

[](float x){return 1/x;} 

Full program

#include <iostream>

void main()
{
    auto y = [](float x){return 1/x;} ;
    std::cout << y(5) << std::endl;
}
|improve this answer|||||
\$\endgroup\$
  • 2
    \$\begingroup\$ In C++14 you can use auto x instead of float x to save a byte. Additionally, main should be declared as returning an int. \$\endgroup\$ – lukeg Mar 31 '17 at 16:26
2
\$\begingroup\$

Ruby, 10 bytes

->x{1.0/x}

Very simple

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Quetzalcoatl, 3 bytes

cfI

c takes input, f converts to a float, and I takes the inverse.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Bean, 7 6 bytes

Equivalent JavaScript:

(1/A)

Bean xxd-style hexdump:

00000000: 4ca5 3a8e 2043                           L¥:. C

Explanation

A is auto-initialized with the 1st input line JSON-parsed. (e.g. 5 is interpreted as JSON and becomes a number), and the program implicitly outputs 1/A.

Edit The "hack" I just realized is that removing the first byte of the AST binary doesn't seem to affect the compilation of the program...

Try the demo here.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Interesting, what's the main cause of this being longer than vanilla JS even though it's basically compressed JS? \$\endgroup\$ – ETHproductions Mar 30 '17 at 18:28
  • \$\begingroup\$ @ETHproductions The overhead of the block scope and I believe binary operators are each 2 bytes (This is due to the binary directly representing the AST of the equivalent JavaScript). Bean really shines with challenges that would typically require several calls to builtins, or when interpreting input as objects automatically saves bytes, or when having a program implicitly input and output is smaller than writing answer as a function where you explicitly input and output. \$\endgroup\$ – Patrick Roberts Mar 30 '17 at 18:38
  • \$\begingroup\$ Weird... I just found an interesting hack. \$\endgroup\$ – Patrick Roberts Mar 30 '17 at 18:51
2
\$\begingroup\$

Forth, 3 bytes

1/f

Try it online

Takes a floating point literal, which in Forth must be in scientific notation, like 5e-4 for 0.0005 or 2e3 for 2000.0. The result will be left on the floating point stack.

Reference on number conversion in Forth.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Actually, 1 byte

ì

From the docs:

8D (ì): pop a: push 1/a

Try It Online

In Seriously, it would be two bytes:

|improve this answer|||||
\$\endgroup\$
  • 3
    \$\begingroup\$ This doesn't work in Seriously because Seriously doesn't do implicit input. You should also provide a TIO link. \$\endgroup\$ – Mego Mar 30 '17 at 18:36
  • \$\begingroup\$ Huh. I must have misremembered. Feel free to edit. \$\endgroup\$ – quintopia Mar 30 '17 at 22:15
  • \$\begingroup\$ Actually, this is 2 bytes. \$\endgroup\$ – Coder-256 Apr 17 '17 at 18:44
  • \$\begingroup\$ It's one Seriously/Actually byte. See the docs. \$\endgroup\$ – quintopia Apr 17 '17 at 23:42
2
\$\begingroup\$

Brachylog, 2 bytes

/₁

Try it online!

For the sake of completeness…

Explanation

/, by default, takes a list of 2 numbers [A, B] as input and unify its output with A divided by B.

When / has a subscript, it takes a single number as input unify its output with that number divided by the subscript. For example, /₄₂ will divide the input number by 42.

The only exception is if the subscript is 1 (because dividing by 1 is kind of useless). In that case, it unifies its output with the inverse of its input.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

dc, 7 6 bytes

Edit: saved 1 byte thanks to Digital Trauma

7k1?/p

Try it online!

Because dc treats the input as commands, negative numbers are recognized using _ as the negative sign, instead of -, which is interpreted as the subtraction command. This is allowed by this meta consensus.

Explanation:

7k           # set precision to 7 digits. This is needed to output at least 4
             #significant figures when the input is '6431' for example)
1?           # push 1, then push input number
/p           # divide and print result
|improve this answer|||||
\$\endgroup\$
  • 1
    \$\begingroup\$ The r is unnecessary with a slight change: 4k1?/p \$\endgroup\$ – Digital Trauma Mar 30 '17 at 18:55
  • \$\begingroup\$ @DigitalTrauma You're right, thanks. I rushed it. I updated the answer. \$\endgroup\$ – seshoumara Mar 30 '17 at 19:37
2
\$\begingroup\$

Java 7, 29 bytes

Golfed:

float i(float x){return 1/x;}

Ungolfed:

float i(float x)
{
    return 1 / x;
}

Pretty straight forward.

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

OCaml, 12

fun x->1./.x

The division of floats is done with the operator /..

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

bc + sh, 14 10 bytes

1/read()<NEWLINE>

Run bc with -l which sets the default scale to 20. That way both input and output have 20 digits after the decimal point.

Edit: Thanks DigitalTrauma for a tip on changing the answer from bc + sh to pure bc. Saved 4 bytes.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG!. I think you can claim 1/read()<NEWLINE> as a 10-scoring pure bc answer. This would include +1 for the use of the -l flag to bc, as per standard rules \$\endgroup\$ – Digital Trauma Mar 31 '17 at 16:35
  • \$\begingroup\$ @DigitalTrauma Thanks for the tip! I'll change the answer. I've never used bc by itself, only inside sh scripts, so I didn't know it is possible to use read() to enter variables. Just found an example in bc man page that does something similar. \$\endgroup\$ – Maxim Mikhaylov Mar 31 '17 at 16:57
  • \$\begingroup\$ Why is it 10 bytes? I count only 8 visible (one-byte) characters and one newline (of you really insist that this be part of the program). Makes 9 bytes. Where's the tenth? \$\endgroup\$ – Alfe Apr 2 '17 at 22:53
  • 1
    \$\begingroup\$ @Alfe Yes, newline counts, since a number can't be read from stdin without it. The 10th byte comes from -l flag that is needed to achieve the required precision. \$\endgroup\$ – Maxim Mikhaylov Apr 2 '17 at 23:09
2
\$\begingroup\$

C#, 7 6 bytes

Saved a byte thanks to David Conrad.

x=>1/x;

Anonymous function which returns the inverse of a number.

Full program with test cases:

using System;

public class Program
{
    public static void Main()
    {
        Func<double, double> f =
        x=>1/x;

        // test cases:
        Console.WriteLine(f(0.5134));
        Console.WriteLine(f(0.5));
        Console.WriteLine(f(2));
        Console.WriteLine(f(2.0));
        Console.WriteLine(f(0.2));
        Console.WriteLine(f(51.2));
        Console.WriteLine(f(113.7));
        Console.WriteLine(f(1.337));
        Console.WriteLine(f(-2.533));
        Console.WriteLine(f(-244.1));
        Console.WriteLine(f(-0.1));
        Console.WriteLine(f(-5));
    }
}
|improve this answer|||||
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't think you need to count the semicolon in C#. Imagine that the lambda was being passed to a function that took a Func<double, double> as a parameter; in that case, it wouldn't be followed immediately by a semicolon. \$\endgroup\$ – David Conrad Mar 31 '17 at 14:20
  • 1
    \$\begingroup\$ AFAIK you should submit separate languages as separate answers. This helps the leaderboard userscript detect them as separate posts. \$\endgroup\$ – dkudriavtsev Mar 31 '17 at 19:16
2
\$\begingroup\$

PHP, 24 bytes

echo(1/(float)$argv[1]);

This is my first answer, tell me if I can somehow shorten it! Try it online!

When trying it online, just change the argument to the desired number n of which you want to get 1/n

Very straightforward approach.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I think you can replace 1 with 1.0 and then remove the (float) for some savings. I tried it in your TIO link and it seemed to work. \$\endgroup\$ – Malivil Apr 18 '17 at 17:59
  • \$\begingroup\$ @Malivil but isn't $argv[1] originally a string and therefore has to be casted to a float? \$\endgroup\$ – dv02 Apr 18 '17 at 18:24
  • \$\begingroup\$ I think it's doing implicit type casting. I tried it out in your TIO link and it was working. I also read though the PHP manual a bit (php.net/manual/en/language.types.type-juggling.php) and it seems like it just changes based on context. \$\endgroup\$ – Malivil Apr 18 '17 at 18:36
2
\$\begingroup\$

Common Lisp, 1 byte

/

Try it online!

|improve this answer|||||
\$\endgroup\$
2
\$\begingroup\$

Julia, 3 bytes

3 bytes saved thanks to @gggg

inv

Try it online!

Returns the matrix inverse.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ inv is just 3 bytes \$\endgroup\$ – gggg Feb 1 '18 at 18:35
1
\$\begingroup\$

CJam, 4 bytes

1rd/

Try it online!

1     e# Push 1
 rd   e# Push input as a double
   /  e# Divide

Alternate solution:

rdW#

rd    e# Push input as a double
  W   e# Push -1
   #  e# Exponentiation
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Fortran 95, 23 bytes

function f(x)
f=1/x
end
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Mathics, 4 bytes

1/#&

Try it online!

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

QBIC, 5 bytes

:?1/a

Explanation:

:    get input from the cmd line, named 'a'
?    PRINT
1/a  1/a
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Scala, 3 bytes

1/_

This defines a lambda equivalent to x => 1/x (_ is a placeholder for the argument). Use by assigning it to a variable, then calling it, like this:

val f: Double => Double = 1/_
f(5) // 0.2
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Racket, 11 bytes

(/ 1(read))

Try it online!

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Hello and welcome to the site! It looks like the .0 is not really necessary (tio). You can assume that the input is a float so you don't need to go through the trouble of having the 1 be a float. \$\endgroup\$ – Ad Hoc Garf Hunter Mar 31 '17 at 4:31
  • \$\begingroup\$ @WheatWizard thanks, and does that mean fractions are acceptable output (eg. 1/5 vs 0.2)? \$\endgroup\$ – assefamaru Mar 31 '17 at 4:39
  • \$\begingroup\$ No, fractions are still not allowed its just that instead of doing (/ 1.0 -33) you can do (/ 1 -33.0) that is put the burden of float casting onto the input instead of your code. If you look at the modified version of your code I provided you will see it still does output a float. \$\endgroup\$ – Ad Hoc Garf Hunter Mar 31 '17 at 4:47
  • \$\begingroup\$ Thanks @WheatWizard, made the edit above. Just realized OP allowed x.0 input format after reading the last three comments under main question. \$\endgroup\$ – assefamaru Mar 31 '17 at 5:06
1
\$\begingroup\$

PHP, 11

<?=1/$argn;

Run with echo <n> | php -nR '<code

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Excel VBA, 7 Bytes

Anonymous VBE immediates window function that takes input from cell [A1] of type variantand expecting a (floating-point) number and outputs its inverse to the VBE immediates window. Does not handle improperly formatted input.

?1/[A1]
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 2 bytes

Ansֿֿ ¹

You could also do 1/Ans (3) or Ans^~1 (4).

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Noodel, 1 byte

A command that takes the first character of a string and places at the end, for numbers takes the reciprocal of the number. The interpreter for Noodel is written in JavaScript which has double precision floating point numbers.

Try it:)


How it works

  # Implicitly pushes the number onto the stack.
ẹ # Takes the reciprocal of the input.
  # Implicitly prints the top of the stack to the screen.
|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Scala, 15 Bytes

(x:Double)=>1/x

Don't think there's a shorter way to do this in Scala.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ The input isn't limited to ints. \$\endgroup\$ – David Conrad Mar 31 '17 at 14:26
  • \$\begingroup\$ Oops. That's what happens when you write code golf solutions at 5 in the morning. Fixed! \$\endgroup\$ – Stefan Aleksić Mar 31 '17 at 16:05
1
\$\begingroup\$

Elixir, 7 bytes

&(1/&1)

Anonymous function defined using the capture operator.

Full program:

f=
&(1/&1)

IO.inspect(f.(0.5134))  # 1.94779898714453

Try it online!

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Emacs Lisp, 11 bytes

(/ 1(read))

Elisp defaults to integer division, so the input will have to be given as floating point, e.g. 1.0 instead of 1. The engine evaluates the (read) statement to get the input and then evaluates the (/ ...) statement, and outputs the answer to stdout.

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

Bash + bc, 12 bytes

bc -l<<<1/$1

bc defaults to integer division, which would be a problem, but running bc with the -l flag loads a math library that allows for floating point division. The $1 takes the first command line argument passed to the Bash script and the <<< passes the string with the expanded argument to bc.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.