# It's Just Rocket Science

Write a program/function that finds the amount of fuel needed to escape Earth's gravity well given the exhaust velocity of the fuel and the amount of mass to transport using the Tsiolkovsky rocket equation: $$\Delta v = v_\text{exhaust}\ln\dfrac{m_\text{start}}{m_\text{end}}$$ where

• $$\\Delta v\$$ is the change in velocity from start to finish (in this case, escape velocity is about 11.2 km/s, so you will use that)
• $$\v_\text{exhaust}\$$ is the exhaust speed of the fuel (you will be given this)
• $$\m_\text{start}\$$ is the starting mass of the ship (i.e. including fuel)
• $$\m_\text{end}\$$ is the ending mass of the ship (i.e. excluding fuel) (you will also be given this)

Equivalently, you have to calculate $$\m_\text{start}-m_\text{end},\$$ which is the mass of the fuel.

The mass you need to get away from Earth will be given in kg*, and the exhaust speed in km/s with precision in the tenths. Return the mass of fuel in kg*. You can take input in any acceptable format, including (but not limited to):

• Mass as integer, exhaust speed as double/float
• Mass as integer, exhaust speed as integer representing tenths (for example, 24 would represent 2.4)
• Mass as string, exhaust speed as string

Output at least with precision to the integer (that is, when rounded to the nearest integer, your answer should be correct), and in any reasonable format (integer, float, string). Standard loopholes apply. Scoring is shortest answer per language wins, as is standard .

Sample implementation in Python:

import math

DELTA_V = 11.2

def fuel(mass: int, exhaust_speed: float) -> float:
ratio = math.exp(DELTA_V / exhaust_speed) # m_start / m_end
return mass * (ratio - 1)


Try it online!

Test cases (note that they aren't exact):

(0, 1) -> 0
(1, 2.4) -> 105.34267539816554
(100, 2.4) -> 10534.267539816554
(100, 100) -> 11.851286064504517
(1000, 4) -> 15444.646771097048
(597, 4) -> 9220.454122344938
(597, 4.2) -> 7994.973908804485


Here is a Stack Snippet to generate both a regular leaderboard and 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=252264; var OVERRIDE_USER=114332; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.rawh\d,e=String.raw\-?\d+\.?\d*,f=String.raw[^\n<>]*,g=String.raw<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>,h=String.raw[^\n\d<>]*,j=String.raw<[^\n<>]+>;return new RegExp(String.raw<${d}>+String.raw\s*([^\n,]*[^\s,]),.*?+String.raw(${e})+String.raw(?=+String.raw${h}+String.raw(?:(?:${g}|${j})${h})*+String.raw</${d}>+String.raw))}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <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> 

* Technically, you can use any unit, as long as it's the same for input and output - it doesn't really matter.

• Sandbox (deleted) Sep 27, 2022 at 16:38

# Raku, 19 18 bytes

*×(e**(11.2/*)-1)


saved one byte by using the built-in constant e instead of the exp function

Try it online!

This is a "WhateverCode" expression, a short way of defining an anonymous function where the lone asterisks mark where the function arguments will go.

• What a beautiful language. Raku really can go the whole stretch from "wow, that looks like a pretty normal programming language I could use to solve real problems" all the way to this answer's keyboard smash of an anonymous function. Sep 28, 2022 at 23:20

# Factor, 24 bytes

[ 11.2 swap / e^ 1 - * ]


Attempt This Online!

       ! 1 2.4
11.2   ! 1 2.4 11.2
swap   ! 1 11.2 2.4
/      ! 1 4.666666666666667
e^     ! 1 106.3426753981655
1      ! 1 106.3426753981655 1
-      ! 1 105.3426753981655
*      ! 105.3426753981655


# JavaScript (ES7), 22 bytes

### Approximation

Expects (ending_mass)(exhaust_speed).

m=>s=>m*73130**(1/s)-m


Try it online!

This is:

$$m\times \left(e^{11.2}\right)^{1/s}-m$$

with $$\e^{11.2}\approx 73130\$$

Maximum error for the test cases: $$\\approx0.027\$$

# JavaScript (ES6), 25 bytes

-1 by using tenths for the exhaust speed, as pointed out by @CommandMaster

### Exact formula

Expects (ending_mass)(exhaust_speed) where the exhaust speed is expressed in tenths.

m=>s=>m*Math.exp(112/s)-m


Try it online!

• If you take exhaust speed as an integer representing tenths 11.2/s will be 112/s for -1 bytes Sep 28, 2022 at 4:21

# Fig, $$\11\log_{256}(96)\approx\$$ 9.054 bytes

*{^mE\x11.2


Try it online!

Forgot to mention that it expects exhaust speed first and then mass.

*{^mE\x11.2  : Full program
\x11.2  : Divides 11.2 by first input
^mE        : e^result
{           : Decrement
*            : Multiply given only one argument so second input is implied

• What's the justification for your score of 9.054 bytes (other than that's what your website says)? Sep 28, 2022 at 4:28
• Nothing about Fig is my decision, it is instead developed by Seggan, but it arose from a recent meta allowing this sort of thing. To my understanding, it is taking the size in some hypothetical system and converting to bytes-based storage. You wind up with n*log_256(96), where n is the number of characters in the source code, 96 is the number of characters in the codepage, and base-256 being bytes-based storage. I believe the relevant meta to be this. Sep 28, 2022 at 4:42

# Python, 31 bytes

lambda m,e:m*(1+7e-9/e)**16e8-m


Attempt This Online!

Avoids the math import by using $$\e^x\approx(1+x/n)^n\$$ for large n.

# Rust, 28 27 bytes

|m,v:f64|m*(11.2/v).exp()-m


Attempt This Online!

• -1 byte by @Steffan
• |m,v:f64|m*(11.2/v).exp()-m saves a byte. Sep 28, 2022 at 3:30

# Desmos, 20 bytes

f(m,v)=me^{11.2/v}-m


Try It On Desmos!

Try It On Desmos! - Prettified

# Jelly,  9  8 bytes

-1 by taking the exhaust velocity in 10ths - thanks Kevin Cruijssen!

112÷Æe’×


A dyadic Link that accepts the exhaust velocity on the left, in tenths, and the mass on the right and yields the fuel mass.

Try it online!

### How?

112÷Æe’× - Link: number v, number m
112      - 112
÷     - divide by v
Æe   - Exp(that)
’  - decrement
× - multiply by m

• One of the input options is "Mass as integer, exhaust speed as integer representing tenths (for example, 24 would represent 2.4)", so you can remove the . and just use 112 with tenths as input for -1 byte. Sep 28, 2022 at 10:44

# I, 50 bytes

I does not have exponentiation, so e^x is approximated with the Taylor series.

*H 1/(inf. i+1p2f *.r)*(11.2/].  *p inf.i H]). +.r

• 1/ should be float division by default Oct 2, 2022 at 9:17
• how does one run this function. all i get is domain error Oct 2, 2022 at 9:24

# Go, 64 bytes

import."math"
func f(m,v float64)float64{return m*Expm1(11.2/v)}


Attempt This Online!

# MathGolf, 10 8 bytes

8D*╠e▬(*


Inputs in the order: $$\v_{exhaust}, m_{end}\$$, where $$\v_{exhaust}\$$ is taken as a float representing tenths (e.g. 24.0).

Try it online.

Explanation:

8D*       # Multiply 8 by 14: 112
╠      # Divide it by the first (implicit) input-float (exhaust speed as tenths)
e▬    # Push e (2.718281828459045) to the power this
(   # Decrement it by 1
*  # Multiply it to the second (implicit) input-integer (mass)
# (after which the entire stack is output implicitly as resulting fuel mass)


: / is used for both integer division (if both arguments are integers) and regular division (if either or both arguments are floats). So I can't take the first input $$\v_{exhaust}\$$ as tenths as an integer.

# C (gcc), 29 bytes

#define f(m,v)m*exp(11.2/v)-m


Try it online!

Update: Removed typdef and unnecessary includes. Thanks to @AZTECCO

• Not a C guy so I don't know if we have a consensus on this that says otherwise but, if not, then you'll need to include the #includes, which it doesn't look like you need, and the typedef in your byte count. Sep 28, 2022 at 11:02
• @Shaggy is right. The -lm flags comes for free and the #include's can be removed, but the typedef should be included. (It's shorter to just use float three times, though.) Sep 28, 2022 at 11:15
• This may solve the problem Sep 28, 2022 at 11:33
• Welcome to code golf, if you haven't already please take a look at the tag info , you can see useful tips for golfing in C here. Sep 28, 2022 at 14:22

# Python, 27 Bytes

lambda m,e:m*73130**(1/e)-m


Try it online

# BQN, 1413 12 bytes

Edit: -1 byte thanks to faun locke
Edit 2: -1 byte by taking input in tenths of km/s (thanks to Kevin Cruijssen's comment)

⊣×1-˜⟜⋆112⊸÷


Try it at BQN REPL

Exhaust speed given as an integer representing tenths of km/s.

Or as a function for 1 more byte: {𝕨×1-˜⋆112÷𝕩} (try it)

        11.2⊸÷   # 11.2 divided by right arg
⋆         # exponent of that
1-˜⟜          # one minus that
⊣×              # times left arg

• -1 byte with After: ⊣×1-˜⟜⋆11.2⊸÷
– user106914
Sep 28, 2022 at 17:10
• @faunlocke - thanks! Sep 28, 2022 at 21:26

# 05AB1E, 11 9 bytes

žrƵBI/m<*


Inputs in the order: $$\v_{exhaust}, m_{end}\$$, where $$\v_{exhaust}\$$ is taken as an integer representing tenths.

Explanation:

žr         # Push constant e: 2.718281828459045
ƵB       # Push compressed integer 112
I/     # Divide it by the first input (exhaust speed as tenths)
m    # Take e to the power this
<   # Decrease it by 1
*  # Multiply it to the second (implicit) input (mass)
# (after which the resulting fuel mass is output implicitly)


See this 05AB1E tip of mine (section How to compress large integers?) to understand why ƵB is 112.

# Vyxal, 9 8 bytes

⁺»?/∆e‹*


Try it Online!

# Charcoal, 18 bytes

Ｉ×Ｎ⊖Ｘ≕math.e∕¹¹·²Ｎ


Try it online! Link is to verbose version of code. Explanation:

  Ｎ                 First input as a number
×                  Multiplied by
≕math.e        Python variable math.e
Ｘ               Rasied to power
¹¹·²   Literal number 11.2
∕       Divided by
Ｎ  Second input as a number
⊖                Decremented
Ｉ                   Cast to string
Implicitly print


# Japt, 9 bytes

Takes mass as the first input and speed, represented as tenths, as the second.

nU*Me#p/V


Try it

nU*Me#p/V     :Implicit input of integers U=mass & V=speed
n             :Subtract U from
U*           :  U multiplied by
Me         :  Euler's Constant raised to the power of
#p       :    112
/V     :    Divided by V


# Python, 45 43 bytes

lambda m,e:m*math.exp(11.2/e)-m
import math


Attempt This Online!

-2 bytes from @att

• -2
– att
Sep 28, 2022 at 1:36
• -18 I don't know if this is still in the spirit of your idea tho Sep 28, 2022 at 6:56
• @SirHawrk I'd recommend posting it as its own answer, since it's so different; it's a good answer though! Sep 28, 2022 at 13:39

# MATLAB, 45 bytes

function y=fuel(m,v) y=m*(exp(11.2/v)-1); end

• Hi! This answer takes input and produces output through variables, which isn't allowed. It also doesn't include a byte count (or shorten variable names for golfiness) or use the typical formatting, which is # in front of the language name and byte count (which makes them title-formatted) and four spaces of indentation before the code, for code formatting. Oct 4, 2022 at 18:06
• what is golfiness? Oct 4, 2022 at 19:16
• all in function, what about now? Oct 4, 2022 at 19:20
• Golfiness as in, how short it is. So getting rid of unnecessary spaces, and shortening variable names (could fuel be shorter?). Oct 4, 2022 at 19:22
• Wonderful, thanks for your answer, I really appreciate as new here to get answers to the basics. I think I am going to leave the 'fuel' as it is, just in case some one takes gasoline nozle for diesel :) Oct 4, 2022 at 19:27