# Reciprocal of a number (1/x)

## 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)

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

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

• – user41805 Mar 30 '17 at 18:04
• @KritixiLithos People can vote as they see fit. Given the simplicity of this challenge, most, if not all answers are something like 1/x. – NoOneIsHere Mar 30 '17 at 18:08
• This isn't objectively specified without very clear detail on accuracy and precision. – Peter Taylor Mar 30 '17 at 18:10
• 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. – Peter Taylor Mar 30 '17 at 20:27
• -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. – feersum Mar 31 '17 at 5:12

# NO!, 31 bytes

NB: Non-competing as language post-dates the challenge

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


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


# HODOR, 100 bytes

NB: Non-competing because why not? I'm never going to win with Hodor!

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)


1)

Walder - Start program

2)

Hodor?! - Take input from STDIN

3)

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

4)

HODOR!! - Output accumulator value as number

5)

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

• "Wylis"? Someone didn't read the books. ;) – Martin Ender Apr 5 '17 at 12:09
• @MartinEnder I read them but couldn't be bothered to look for his name in them. They are other 4000 pages long altogether. – caird coinheringaahing Apr 5 '17 at 12:11
• – Martin Ender Apr 5 '17 at 12:11
• @MartinEnder I can't believe I have defiled Hodor's memory like this! (Now I've got to go change all the answers!) – caird coinheringaahing Apr 5 '17 at 12:22

# Pyth, 3 2 bytes

-1 byte thanks to Steven Hewitt

c1


c is float division, with 1 and implicit input.

• Pyth can fill in the Q implicitly, so c1 works just as well. – Steven H. Apr 8 '17 at 12:59

# SenseTalk, 16 bytes

params r
put 1/r


Explanation

params r # accept input
put 1/r  # get the reciprocal


# Keg, 1 byte

⑱


Try it online!

## Keg, 3 bytes(SBCS)

1¿/


TIO Divide 1 by friendly input

• ⑱ for 1 byte. – Lyxal Jan 20 at 22:02

## W, 3 bytes

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

1S/


## Explanation

a1S  % Stack : 1 a
/ % Divide.(1/a)
% Output.


# Rogex, 15 bytes

701300001600200


Try it online!

The actual language isn't on TIO yet, so a python 3.8 interpreter with the program in the code section and the python interpreter split in the header and footer is provided

Rogex is a newly developed language that I've recently discovered, so I though I'd give it a crack and write an answer.

## Explained

701 300 # Set the buffer to 1 and place it in cell 0
001     # Get numeric input and place it into the buffer
600 200 # Divide cell 0 (1) by the buffer (input) and print


## Jellyfish, 3 bytes

p%i


Try it online!

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

# Gol><>, 4 bytes

1I,h


# 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


## Racket 7 bytes

(/ 1 x)


Full function:

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


Testing:

(f 1.56)


Output:

0.641025641025641


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

# JavaScript(ES7), 8 bytes

x=>x**-1


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

• @fəˈnɛtɪk Oh dammit. Now I have to rollback to x**-1. – Matthew Roh Apr 5 '17 at 13:02
• ** does not exist in ES6, it was added in ES7, which is why I specified your answer was ES7 – fəˈnɛtɪk Apr 5 '17 at 13:51
• 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. – fəˈnɛtɪk Apr 5 '17 at 14:01

## Python 2.7, 17 25 bytes

Full program:

print'%.4f'%(1.0/input())


# 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

(/)1


Currying FTW!

• alternatively (1/) – Zwei Apr 25 '17 at 23:32

# 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"]]


# 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

• 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... – user58988 Apr 17 '17 at 18:52

# Convex, 1 byte

¹


Try it online!

## 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)


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

• 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. – steenbergh Apr 18 '17 at 14:31

# Perl 5, 7 bytes

The obvious subroutine.

{1/pop}

• I was under the impression that you could only omit the sub when passing it to a subroutine with a & prototype. – a spaghetto May 1 '17 at 18:39
• @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." – msh210 May 1 '17 at 19:54
• Still, the result is not something that is callable as it stands. I would say it is invalid. – Ton Hospel Feb 1 '18 at 19:08

# 8087 machine code, 4 bytes

d9 e8   |   fld1
d8 f1   |   fdiv st0, st1


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

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

# ARBLE, 3 bytes

1/x


Try it online!

# Aceto 1.0, 4 3 bytes non-competing

Non-competing because the challenge predates Aceto. Assumes input number is on the stack, and leaves it on the stack.

1s:


1 pushes 1 on the stack, s swaps the top two values, and : does floating point division.

Also, this is the first Aceto answer!

edit: Saved 1 byte

# Attache, 4 bytes

1&/


Try it online!

This is division (/) left-bonded with 1, which is equivalent to reciprocal.

# Bash, 15 bytes

dc -e"Fk$1_1^p"  Try it online! dc ::Use dc calculation -e ::Evaluate argument as dc code " " ::Quote Fk ::F sig-figs (F is hex for 15)$1       ::$1 is initial value (the first argument) _1^ ::Raise$1 to power of -1
p  ::Print result


# KoopaScript, 48 bytes

def a i inp;setath o 1 / \%vuserInput;print \%vo


And how it works (KS isn't really golfable yet but it's fun nonetheless):

def a i                                          - define a function and call it a lot
inp;                                     - pause execution until input
setath o 1 / \%vuserInput;           - set 'o' to 1 / the input
print \%vo - output 'o'


Try it online (paste the code into the left-hand box, press enter, then type a number, press enter, etc)

Now that KS has input, I can finally start using it for stuff that involves interaction :D (Tell me if this should be non-competing :P)

# AWK, 10 7 bytes

$0=1/$0


Usage:

awk '$0=1/$1' <<< "some number here"


or use the TIO link : Try it online!

Explanation: Replace the input line with its reciprocal. This is then evaluated and the entire line is printed if the evaluation in non-zero. Since the result can't be 0` we don't need to worry about not receiving output.