28
\$\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\$
45
  • 24
    \$\begingroup\$ Please stop upvoting trivial answers \$\endgroup\$
    – user41805
    Commented Mar 30, 2017 at 18:04
  • 17
    \$\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\$ Commented Mar 30, 2017 at 18:08
  • 9
    \$\begingroup\$ This isn't objectively specified without very clear detail on accuracy and precision. \$\endgroup\$ Commented Mar 30, 2017 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\$ Commented Mar 30, 2017 at 20:27
  • 11
    \$\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
    Commented Mar 31, 2017 at 5:12

98 Answers 98

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!

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

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

\$\endgroup\$
1
\$\begingroup\$

Pyth, 3 2 bytes

-1 byte thanks to Steven Hewitt

c1

c is float division, with 1 and implicit input.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Pyth can fill in the Q implicitly, so c1 works just as well. \$\endgroup\$
    – Steven H.
    Commented Apr 8, 2017 at 12:59
1
\$\begingroup\$

8087 machine code, 4 bytes

d9 e8   |   fld1
d8 f1   |   fdiv st0, st1

The obvious/trivial solution. Expects input in register st0.

\$\endgroup\$
1
\$\begingroup\$

SenseTalk, 16 bytes

params r
put 1/r

Explanation

params r # accept input
put 1/r  # get the reciprocal
\$\endgroup\$
1
\$\begingroup\$

Keg, 1 byte

Try it online!

Keg, 3 bytes(SBCS)

1¿/

TIO Divide 1 by friendly input

\$\endgroup\$
1
  • \$\begingroup\$ for 1 byte. \$\endgroup\$
    – lyxal
    Commented Jan 20, 2020 at 22:02
1
\$\begingroup\$

W, 3 bytes

You know, we can't beat the built-ins.

1S/

Explanation

a1S  % Stack : 1 a
   / % Divide.(1/a)
     % Output.
\$\endgroup\$
1
\$\begingroup\$

NO!, 31 bytes

NO! has 6 valid tokens: NOno!? and commands are made up of NO with the number of O determining the command.

NOOOOO?no!NOOOOOOOOOOO
NOOOOOOOO?no

###More readable

NOOOOO?                 NOOOOO is the divide command and ? starts the arguments
       no!              no is 1 and ! separates the arguments            
          NOOOOOOOOOOO  This takes input from STDIN.

NOOOOOOOO?              This outputs the result of the       line
          no                                           first 

The equivalent pseudocode:

output divide 1, input
\$\endgroup\$
1
\$\begingroup\$

HODOR, 100 bytes

Walder
Hodor?!
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor,
HODOR!!
HODOR!!!

If you must know how it works, I'll tell you.

Explanation

Walder                                                                       Hodor hodor
Hodor?!                                                                     Hodor hodor hodor HODOR
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor,        Hodor hodor hodor hodor hodor hodor
HODOR!!                                                                     Hodor hodor hodor hodor hodor
HODOR!!!                                                                    Hodor hodor (Hodor hodor hodor)

Walder - Start program

Hodor?! - Take input from STDIN

Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor, - Change accumulator value to it's reciprocal

HODOR!! - Output accumulator value as number

HODOR!!! - Kill Hodor (End the program)

\$\endgroup\$
4
  • \$\begingroup\$ "Wylis"? Someone didn't read the books. ;) \$\endgroup\$ Commented Apr 5, 2017 at 12:09
  • \$\begingroup\$ @MartinEnder I read them but couldn't be bothered to look for his name in them. They are other 4000 pages long altogether. \$\endgroup\$ Commented Apr 5, 2017 at 12:11
  • \$\begingroup\$ awoiaf.westeros.org/index.php/Hodor :) \$\endgroup\$ Commented Apr 5, 2017 at 12:11
  • \$\begingroup\$ @MartinEnder I can't believe I have defiled Hodor's memory like this! (Now I've got to go change all the answers!) \$\endgroup\$ Commented Apr 5, 2017 at 12:22
1
\$\begingroup\$

Go, 34 bytes

func(a float64)float64{return 1/a}

Attempt This Online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 5 bytes

recip

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pyt, 1 byte

Try it online!

Just another language with a built-in one-byte reciprocal function

\$\endgroup\$
1
\$\begingroup\$

Pascal, 40 bytes

The built-in data type real provides an implementation-defined approximation.

function f(x:real):real;begin f:=1/x end
\$\endgroup\$
0
\$\begingroup\$

Jellyfish, 3 bytes

p%i

Try it online!

Unary % computes the reciprocal. i is input, p is output.

\$\endgroup\$
0
\$\begingroup\$

Gol><>, 4 bytes

1I,h

Online interpreter link

\$\endgroup\$
0
\$\begingroup\$

Dyvil, 5 Bytes

1 / _

Unfortunately we need the extra white space because /_ would be a single operator, and 1/ _ would parse differently

Usage:

let f: double -> double = 1 / _
print(f(2)) // 0.5
\$\endgroup\$
0
\$\begingroup\$

Racket 7 bytes

(/ 1 x)

Full function:

(define (f x)
  (/ 1 x))

Testing:

(f 1.56)

Output:

0.641025641025641
\$\endgroup\$
0
\$\begingroup\$

REXX, 12 bytes

say 1/arg(1)

Divides 1 by first argument. Precision is decided by NUMERIC DIGITS but defaults to at least 9 decimals.

\$\endgroup\$
0
\$\begingroup\$

JavaScript(ES7), 8 bytes

x=>x**-1

f=x=>x**-1;
console.log(f(0.5134));

\$\endgroup\$
3
  • \$\begingroup\$ @fəˈnɛtɪk Oh dammit. Now I have to rollback to x**-1. \$\endgroup\$ Commented Apr 5, 2017 at 13:02
  • \$\begingroup\$ ** does not exist in ES6, it was added in ES7, which is why I specified your answer was ES7 \$\endgroup\$ Commented Apr 5, 2017 at 13:51
  • \$\begingroup\$ The Seventh Edition, also known as ECMAScript 2016, intended to continue the themes of language reform, code isolation, control of effects and library/tool enabling from ES2015, includes two new features: the exponentiation operator (**) and Array.prototype.includes. \$\endgroup\$ Commented Apr 5, 2017 at 14:01
0
\$\begingroup\$

Python 2.7, 17 25 bytes

Full program:

print'%.4f'%(1.0/input())
\$\endgroup\$
0
\$\begingroup\$

CGL (CGL Golfing Language), 6 bytes (non-competing)

This language postdates this challenge.

-÷Ⓧ

Explanation:

- decrements the current stack, so it is now -1, where input is placed

÷ Divides the first element of the stack by the second if it exists, otherwise (this case) it divides 1 by the first (reciprocal)

Output the last stack item (the result of ÷) and exit

\$\endgroup\$
0
\$\begingroup\$

Haskell, 4 bytes

(/)1

Currying FTW!

\$\endgroup\$
1
  • \$\begingroup\$ alternatively (1/) \$\endgroup\$
    – Zwei
    Commented Apr 25, 2017 at 23:32
0
\$\begingroup\$

Axiom, 57 bytes

f(x)==(y:=abs(x);y>9999 or y<0.0001=>"ObjFloatErr ";1./x)

test code and results

(21) -> [[i,f(i)] for i in [-2,-1,-0.0001,-0.00001,9999,10000]]
   (21)
   [[- 2.0,- 0.5], [- 1.0,- 1.0], [- 0.0001,- 10000.0],
    [- 0.00001,"ObjError 1/x"], [9999.0,0.0001000100 0100010001],
    [10000.0,"ObjError 1/x"]]
\$\endgroup\$
0
\$\begingroup\$

Fourier (Non-Competing), 79 bytes

1~RI~X<0{1}{0-1~R45a}X*R~XL*2+2/2~UX{1}{0~U}10P10/X~DL+U~p10Pp~TD/To*T~A46aD-Ao

Try it online!

This is non-competing for two reasons:

  • Firstly, it does not fulfil the spec (it only works for inputs in the range -10 <= x <= 10
  • Secondly, it uses the functions L and P which were added after the writing of this challenge

So, this answer poses a challenge: can you complete this challenge in Fourier in the range -9999 <= x <= 9999? There are two bounties up for grabs:

  • 100 Rep Bounty for the first solution to complete this task without using the new functions L (log 10) and P (power)
  • 50 Rep Bounty for the shortest solution to complete this task using the new functions L (log 10) and P (power)

Note that on the Fourier github repo (https://github.com/beta-decay/Fourier/tree/master/fourIDE/editor) the FourIDE is up to date with L and P.

To-do list

  • Add explanation of code
\$\endgroup\$
1
  • \$\begingroup\$ For x=0 the 1/x=1/0 is not possible so the domain of function 1/x has to be [-a, -e] [e,a] for some 'a' big enough for them and 'e' little enough... \$\endgroup\$
    – user58988
    Commented Apr 17, 2017 at 18:52
0
\$\begingroup\$

Convex, 1 byte

¹

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Jelly , 11 Bytes

²Nṭ1,0ÆrḢ×Ṡ

This works without the built-in inverse function . (Who uses that anyway?).

Try it online!

How it works

²Nṭ1,0ÆrḢ×Ṡ
   1,0      # Look at the list [1,0]
  ṭ         # Append (to the end)
²N          #  the negative of the square of the input
      Ær    # Find the roots to the polynomial with coefficients corresponding to the list as [greater root,lower root] pair
        Ḣ   # Head; get the first element of the roots (always positive)
         ×Ṡ # Multiply by the sign of the input (to accommodate negative input)
\$\endgroup\$
0
\$\begingroup\$

Batch, 69 67 + 39 (vbs section) = 106 bytes

a.bat

@for /f "skip=1" %%n in ('cscript //nologo b.vbs 1/%1')do @echo %%n

Explanation:

  • call VBScript to calculate 1/argument
  • return the result

b.vbs

WScript.Echo Eval(WScript.Arguments(0))

Explanation:(my guess, I'm not good at VBS)

  • return the result calculated by Eval

Test cases

called from command line:

>a.bat 0.5134
1.94779898714453

>a.bat -0.5
-2

Batch can't handle floating point division....

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I can't test VBScript, but my feeling is, that if you change the VBS to WScript.Echo 1/WScript.Arguments(0), and change "1/%1" into ` "%1"`, you could save some bytes. \$\endgroup\$
    – steenbergh
    Commented Apr 18, 2017 at 14:31
0
\$\begingroup\$

Perl 5, 7 bytes

The obvious subroutine.

{1/pop}
\$\endgroup\$
3
  • \$\begingroup\$ I was under the impression that you could only omit the sub when passing it to a subroutine with a & prototype. \$\endgroup\$ Commented May 1, 2017 at 18:39
  • \$\begingroup\$ @quartata, perldoc perlsub says: "The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code." \$\endgroup\$
    – msh210
    Commented May 1, 2017 at 19:54
  • \$\begingroup\$ Still, the result is not something that is callable as it stands. I would say it is invalid. \$\endgroup\$
    – Ton Hospel
    Commented Feb 1, 2018 at 19:08
0
\$\begingroup\$

Groovy, 9 bytes

{1.0g/it}

Needs the .0g to denote big decimal notation on the 1, making the it unbox itself as a BigDecimal.

Input of 7.29349129124513204632593467635245678734521456789

Results in 0.13710854789123656486815482305643737234188188122

If you use an input of 214700000000000, however, without the .0g...

You get an error or nothing.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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