[Question]
  [
Your task is to write a [program or a function](https://codegolf.meta.stackexchange.com/a/2422/60340) that [outputs](https://codegolf.meta.stackexchange.com/q/2447/60340) `n` random numbers from interval [0,1] with fixed sum `s`.
# Input
`n, n≥1`, number of random numbers to generate
`s, s>=0, s<=n`, sum of numbers to be generated
# Output
A random `n`-tuple of floating point numbers with all elements **from the interval [0,1]** and sum of all elements equal to `s`, output in any convenient unambiguous way. All valid `n`-tuples have to be equally likely within the limitations of floating point numbers.
This is equal to uniformly sampling from the intersection of the points inside the `n`-dimensional unit cube and the `n-1`-dimensional hyperplane that goes through `(s/n, s/n, …, s/n)` and is perpendicular to the vector `(1, 1, …, 1)` (see red area in Figure 1 for three examples). 
[![Examples with n=3 and sums 0.75, 1.75 and 2.75](https://i.stack.imgur.com/N6b7k.png)](https://i.stack.imgur.com/N6b7k.png)
Figure 1: The plane of valid outputs with n=3 and sums 0.75, 1.75 and 2.75
# Examples
```
n=1, s=0.8 → [0.8]
n=3, s=3.0 → [1.0, 1.0, 1.0]
n=2, s=0.0 → [0.0, 0.0]
n=4, s=2.0 → [0.2509075946818119, 0.14887693388076845, 0.9449661625992032, 0.6552493088382167]
n=10, s=9.999999999999 → [0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999]
```
# Rules
* Your program should finish under a second on your machine at least with `n≤10` and any valid s.
* If you so wish, your program can be exclusive on the upper end, i.e. `s<n` and the output numbers from the half-open interval [0,1) (breaking the second example)
* If your language doesn't support floating point numbers, you can fake the output with at least ten decimal digits after the decimal point.
* Standard loopholes are disallowed and standard input/output methods are allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest entry, measured in bytes, wins.
  
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~122~~ 115 bytes
```
N=>W=S=>2*S>N?W(N-S).map(t=>1-t):(t=(Q=s=>n?[r=s-s*Math.random()**(1/--n),...r>1?[++Q]:Q(s-r)]:[])(S,n=N),Q?t:W(S))
```
[Try it online!](https://tio.run/##fY3BbsIwEETv@ZLdJN7aIA5JWefGrZEiH3KIImEFKEFgI9vq76ccqVQ4zZPmaeZif2ycwnxPwvnDcdnx0rLu2bBe5Ua3TQ@tMEg3e4fEWomE9QOg48jaNUPgKGL@ZdOZgnUHfwPMc1AfQjgsiSho1QxF0Y11B1EEHOthRDCl4xbLrkl1DwZxySbvor8e6eq/YQdKImyQLn52@3KP/7SSpFRvjYqqqnphYJadfICZ5ee8VVI@oijw78Ya4elg@QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~144~~ ~~128~~ 119 bytes
```
from random import*
def f(n,s):
 r=min(s,1);x=uniform(max(0,r-(r-s/n)*2),r);return n<2and[s]or sample([x]+f(n-1,s-x),n)
```
[Try it online!](https://tio.run/##RY3BDoIwEETv/Yo9dnVBqJqIypcYDySAktgt2UJSvx6riO5lXmayM/1zuDs209SKsyAV11E62zsZVqpuWmg1k8ejAiltx9pTjqdQjty1Tqy2VdAZSaIl8RvGlUESPEkzjMLAZxP7Lv7qBHxl@0ejL@G6jo1JTj4JSIzTe@O2bIRynlPQS8cDBPKj1QGVuuktQZ5mGCknyNLDm8yPYrqd04/3oR2B@X5kBEVa/G8x9zGfXg "Python 2 – Try It Online")
---
* -20 bytes, thanks to Kevin Cruijssen
[Answer]
# Java 8, ~~194~~ ~~188~~ ~~196~~ ~~237~~ 236 bytes
```
n->s->{double r[]=new double[n+1],d[]=new double[n],t;int f=0,i=n,x=2*s>n?1:0;for(r[n]=s=x>0?n-s:s;f<1;){for(f=1;i-->1;)r[i]=Math.random()*s;for(java.util.Arrays.sort(r);i<n;d[i++]=x>0?1-t:t)f=(t=Math.abs(r[i]-r[i+1]))>1?0:f;}return d;}
```
+49 bytes (188 → 196 and 196 → 237) to fix the speed of test cases nearing 1, as well as fix the algorithm in general.
[Try it online](https://tio.run/##lZRNb6MwEIbv/RUWJ2jAQCjqAoWo0mqlPexlu7eIgxtM6y4xkW3aRlV@e3YwJORb2VEExn7nYTwx7xt5J85b8Xc9q4iU6Bdh/OsGIamIYjP0Bqu4UazCZcNnitUc/@gHDz@5oi9U2BdF3@vmuaI2KvR9mmcZKlGK1tzJpJN9ddNITPOU04@Nio/83C4O5nJbJYwrVKaezVJuf6bjW5nxiR97SVkLU4Akleln5k24I2OZlA9@Yn21S2XqJ8xxMngWU5anv4h6xYLwop6b1q3U6cMmHoUgS4llLZQprIQ98KSYstEo12zfUbGyytRUHYY8S7OFOnCBsi0r8ydeXCYrQVUjOCqS1TqBhsJvARuBnvatfa9ZgebQbvNJCcZfpjkiVtt6hBSVyvRthDz8zUrQXrgu@vNKkYQMaBxTdI6YRKT6gJpbvetDe@E@gMYa5J0APVaVJkC@oAPDc8ea4e0U49n/y/C9M5Au/C2rhbxTQV4oqsuexWS8I92yNhOHmwtPFXaaGfabG4cDJACIf3p3pyAgdQOABDgIAozxALoD0Ph6EEjdO11NuN@l8HpGOLR6BxJCIXfXtwWkbqgZ0X4hEb4/hJxjtNJNJdF9eMiJoqs5UbTlRNExZwhNvMQZYoc4xP4JCK4/30F/AvzD4@0ffyTnGP72I@koq84kdt1BY1vP4xsDRbK3iI2fIkFlUymglJgsFtXS5FY/kFaipU9LCe/GdaPwAoxGVdw0eGqM@MhIkITBBeGRK6q6cyuze6/Vp258XE8@NXOo59hQlaBkvknEsgHzPV9hC4H/k7S5MTJGW/SFnN9a4wAZzWoh6ExNINPcpqapnBhLKo3Y4LVhnSfpldXNav0P)
**Explanation:**
Uses the approach in [this StackoverFlow answer](https://stackoverflow.com/a/8064754/1682559), inside a loop as long as one of the items is still larger than 1.  
Also, if `2*s>n`, `s` will be changed into `n-s`, and a flag is set to indicate we should use `1-diff` instead of `diff` in the result-array (thanks for the tip *@soktinpk* and *@l4m2*).
```
n->s->{              // Method with integer & double parameters and Object return-type
  double r[]=new double[n+1]
                     //  Double-array of random values of size `n+1`
         d[]=new double[n],
                     //  Resulting double-array of size `n`
         t;          //  Temp double
  int f=0,           //  Integer-flag (every item below 1), starting at 0
      i=n,           //  Index-integer, starting at `n`
      x=             //  Integer-flag (average below 0.5), starting at:
        2*s>n?       //   If two times `s` is larger than `n`:
         1           //    Set this flag to 1
        :            //   Else:
         0;          //    Set this flag to 0
  for(r[n]=s=        //  Set both the last item of `r` and `s` to:
       x>0?          //   If the flag `x` is 1:
        n-s          //    Set both to `n-s`
       :             //   Else:
        s;           //    Set both to `s`
      f<1;){         //  Loop as long as flag `f` is still 0
    for(f=1;         //   Reset the flag `f` to 1
        i-->1;)      //   Inner loop `i` in range (n,1] (skipping the first item)
      r[i]=Math.random()*s;
                     //    Set the i'th item in `r` to a random value in the range [0,s)
    for(java.util.Arrays.sort(r);
                     //   Sort the array `r` from lowest to highest
        i<n;         //   Inner loop `i` in the range [1,n)
        ;d[i++]=     //     After every iteration: Set the i'th item in `d` to:
          x>0?       //      If the flag `x` is 1:
           1-t       //       Set it to `1-t`
          :          //      Else:
           t)        //       Set it to `t`
      f=(t=Math.abs( //    Set `t` to the absolute difference of:
            r[i]-r[i+1])) 
                     //     The i'th & (i+1)'th items in `r`
        >1?          //    And if `t` is larger than 1 (out of the [0,1] boundary)
         0           //     Set the flag `f` to 0
        :            //    Else:
         f;}         //     Leave the flag `f` unchanged
  return d;}         //  Return the array `d` as result
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 153 bytes
```
(n,s)=>s+s>n?g(n,n-s).map(r=>1-r):g(n,s)
g=(n,s)=>{do(a=[...Array(n-1)].map(_=>Math.random()*(s<1?s:1))).map(r=>t-=r,t=s);while(t<0|t>=1);return[...a,t]}
```
[Try it online!](https://tio.run/##bYxBbsIwEEX3nCLLGWqPYuiiEMaIA3CCClUWCYEq2GjGBVWlZ08BVVWr8nf/6f3/Go5B17I7ZBtT3fQb7iEaRfb6oD7O20uLVpH24QDC3lnBaXtTBi1/qx91gsDPRLQQCe8QrcPVbfHCfhnyliTEOu0Bh6AzN9epQ/y5zJbFZFasTttd10Celefs2WElTX6TeP0NJq8@@3WKmrqGutTCBpwpSnpCrAZ/@dgUYyr/89HVv8MfTTG6x11piglNfuXi9F8 "JavaScript (Node.js) – Try It Online")
[Answer]
## C++11, ~~284~~ 267 bytes
-17 bytes thanks to Zacharý  
Uses C++ random library, output on the standard output
```
#include<iostream>
#include<random>
typedef float z;template<int N>void g(z s){z a[N],d=s/N;int i=N;for(;i;)a[--i]=d;std::uniform_real_distribution<z>u(.0,d<.5?d:1-d);std::default_random_engine e;for(;i<N;){z c=u(e);a[i]+=c;a[++i]-=c;}for(;i;)std::cout<<a[--i]<<' ';}
```
To call, you just need to do that :
```
g<2>(0.0);
```
Where the template parameter ( here, 2 ) is N, and the actual parameter ( here, 0.0 ) is S
[Answer]
# C, ~~132~~ ~~127~~ ~~125~~ ~~118~~ ~~110~~ 107 bytes
*-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
i;f(s,n,o,d)float*o,s,d;{for(i=n;i;o[--i]=d=s/n);for(;i<n;o[++i%n]-=s)o[i]+=s=(d<.5?d:1-d)*rand()/(1<<31);}
```
[Try it online!](https://tio.run/##XZJPb9QwEMXPyacYFVVyduMNy78DTkAIATdAcOBQrdA0dlKriSeyHcS26lcnjLMLSJzijH8z815eWtkO6PplsaoToXQllbroBsK4oTKUWt135IVtnLKKrqS0h0Y3oXKFSnVla8fl7dZeuoNsQkFX9rBtQiN0vXv@Wr/cS11sPDotikrs6/rpvlAPS1W9@4njNBiYPPUeR4gE0YQI8cZAN7s2WnIlaDIBHEVoaXYRMMCEPgJ1Kxfm69GGwOQuzx9Z1w6zNlCHqC3tbl7lueWeEa0TRX6fZ1X1xvfzaFwMebY6hAANPNm9UHkW7J35HsFx4ZnKE/zVGA1fPn4A8WlKanAoGFuttAO1t6IoTuBbbzAaQAfoPR6TlRDJm1WjxojnbRtAnt7iwN2CzaWV1In17u8sGqc5plbr@iSTIwFmke@zBHz2yRTNpy@1LmSKkzgbsLziseJHDU4B58Kisyk1deLisoMLnsURnde998b8G5SU4w@yGkYzkj/CYPA2iWBKJAUPy6@2G7APi/zmSHoTZ@9kPE7mVDDjFI/ymvTx9G45YtvaKP8kKrXhv81jOv@HsMLf)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~221~~ 201 bytes
*Clean, code-golf, or random numbers. Pick two.*
```
import StdEnv,Math.Random,System._Unsafe,System.Time
g l n s#k=toReal n
|s/k>0.5=[s/k-e\\e<-g l n(k-s)]
#r=take n l
#r=[e*s/sum r\\e<-r]
|all((>)1.0)r=r=g(tl l)n s
```
# 
```
g(genRandReal(toInt(accUnsafe time)))
```
[Try it online!](https://tio.run/##PY8xT8MwEIX3/ApLWWzUpOnAhjvBUAkk1MDUVuhwLiGKfUb2BalSfzvBaUS3@07vvbtnLAJNzjejReGgp6l33z6wqLl5op/VC/BXuQdqvFvV58joyo93itDiP771DrNOWEEi5oNmv0dIkF3iethW5b0@pKHA4xEfiqtMDkVUpywPmmHAZLPzfMC7uI6jE@GqDKfsAtZKuVWbslJBB91JtsKqdGaqGQJnuUCLDomj0GJTJabRfWJIVJUztiMZ7j2lRSc7pLnH/J1kvyOWYMxSRXDqoJTKtLxZbtFLppp@TWuhi1Oxe54ezwSuNwu8WuDWB/cH "Clean – Try It Online")
Partial function literal `:: (Int Real -> [Real])`. Will only produce new results once per second.  
Accurate up to at least 10 decimal places.
[Answer]
# [R](https://www.r-project.org/), 99 bytes (with `gtools` package)
```
f=function(n,s){if(s>n/2)return(1-f(n,n-s))
while(any(T>=1)){T=gtools::rdirichlet(1,rep(1,n))*s}
T}
```
[Try it online!](https://tio.run/##TYpNCoMwEIX3niLLmRKt0VKqEE/hBYomOiCjJJFSxLOncde3eB/vx8Votd15CLQysPR4kAXf8b1CZ8LuGFRu08C5R8w@My0G3vyFvtMK8ej1FNZ18W3rRnI0zIsJoKQzW3JGvPkz689oUxJl8cLMQi1FfbFKzcWHFBVmmyMOkH6lFE3R/AmlGGmi4LV6YvwB "R – Try It Online")
We wish to sample uniformly from the set \$\tilde{\mathcal A}=\{w\_1,\ldots,w\_n: \forall i, 0<w\_i<1; \sum w\_i=s\}\$. I'll divide all the \$w\_i\$ by \$s\$ and instead sample from \$\mathcal A=\{w\_1,\ldots,w\_n: \forall i, 0<w\_i<\frac1s; \sum w\_i=1\}\$.
If \$s=1\$, this is easy: it corresponds to sampling from the \$Dirichlet(1, 1, \ldots, 1)\$ [distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution) (which is the uniform over the simplex). For the general case \$s\neq 1\$, we use rejection sampling: sample from the Dirichlet distribution until all entries are \$<1/s\$, then multiply by \$s\$.
The trick to mirror when \$s>n/2\$ (which I think [l4m2 was the first](https://codegolf.stackexchange.com/a/165050/86301) to figure out) is essential. Before I saw that, the number of iterations in the rejection sampler exploded for the last test case, so I spent a *lot* of time trying to sample efficiently from well-chosen truncated Beta distributions, but it is not necessary in the end.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~92~~ 90 bytes
```
If[2#2>#,1-#0[#,#-#2],While[Max[v=Differences@Sort@Join[{0,#2},RandomReal[#2,#-1]]]>1];v]&
```
[Try it online!](https://tio.run/##VcuxCsIwFIXh3acoXHC6lSR1sEhLBxcFQeLgcLlDqCkNtCnUUATxXXwWXyw6tmf7Dvy9Ca3tTXC1iTop4rEhBaoElCkIAoQUFOOtdZ2ls3nSVBxc09jR@to@quswhuo0OE8vgaDeqI2/D722piNQ/1gycyl5P/E6XkbnQ1J9P5okis2OV7Mnw2xhhWLhLaqFpcB8k8/G8Qc "Wolfram Language (Mathematica) – Try It Online")
Un-golfed code:
```
R[n_, s_] := Module[{v},
  If[s <= n/2,             (* rejection sampling for s <= n/2:                        *)
    While[
      v = Differences[Sort[
            Join[{0},RandomReal[s,n-1],{s}]]];         (* trial randoms that sum to s *)
      Max[v] > 1           (* loop until good solution found                          *)
    ];
    v,                     (* return the good solution                                *)
    1 - R[n, n - s]]]      (* for s > n/2, invert the cube and rejection-sample       *)
```
---
Here is a solution that works in **55 bytes** but for now (Mathematica version 12) is restricted to `n=1,2,3` because `RandomPoint` refuses to draw points from higher-dimensional hyperplanes (in TIO's version 11.3 it also fails for `n=1`). It may work for higher `n` in the future though:
```
RandomPoint[1&~Array~#~Hyperplane~#2,1,{0,1}&~Array~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H6Rg@z8oMS8lPzcgPzOvJNpQrc6xqCixsk65zqOyILWoICcxL7VO2UjHUKfaQMewFi4dq/Y/oAioQ8Hh0IKgaCMdAz2LWC4kEWMdYxQ@UAWavBE6X88SCcT@BwA "Wolfram Language (Mathematica) – Try It Online")
Un-golfed code:
```
R[n_, s_] :=
  RandomPoint[                           (* draw a random point from *)
    Hyperplane[ConstantArray[1, n], s],  (* the hyperplane where the sum of coordinates is s *)
    1,                                   (* draw only one point *)
    ConstantArray[{0, 1}, n]]            (* restrict each coordinate to [0,1] *)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~122~~ ~~217~~ 208 bytes
```
import System.Random
r p=randomR p
(n#s)g|n<1=[]|(x,q)<-r(max 0$s-n+1,min 1 s)g=x:((n-1)#(s-x)$q)
g![]=[]
g!a|(i,q)<-r(0,length a-1)g=a!!i:q![x|(j,x)<-zip[0..]a,i/=j]
n%s=uncurry(!).(n#s<$>).split<$>newStdGen
```
[Try it online!](https://tio.run/##TY5Ba4QwEIXv/oqRdSGhmuqhlIrpqVB6KuwexUO2BjdbM8Yk0mzxv9t06aFzeW/mfQ/mLNynHMdtU9pM1sPx6rzU7CCwn3RiwXB7swcwCcGdo8OKTcXbbiUhn2lTWKJFgDJzBd5VuVYIFUSKh5oQLCq6I64INJtpMqRtF4tRxUrUX7nMR4mDP4OI7MBFmqp6TtuwkkseIvGtTFsy1olc3fNLl@De8QU/FmuvJKXs96Ume6bMmVH56FB@HX3/KnHTQiHvpwTi9K4pqnL/xB4foK7h7b19mZbTKLtbaqxCH5l/SwZu0fG0/QA "Haskell – Try It Online")
Sometimes the answers are slightly off due, I assume, to floating point error. If it's an issue I can fix it at a cost of 1 byte. I'm also not sure how uniform this is (pretty sure it's fine but I'm not all that good at this kind of thing), so I'll describe my algorithm.
Basic idea is to generate a number `x` then subtract it from `s` and recur until we have `n` elements then shuffle them. I generate `x` with an upper bound of either 1 or `s` (whichever is smaller) and a lower bound of `s-n+1` or 0 (whichever is greater). That lower bound is there so that on the next iteration `s` will still be less than or equal to `n` (derivation: `s-x<=n-1` -> `s<=n-1+x` -> `s-(n-1)<=x` -> `s-n+1<=x`).
EDIT: Thanks to @michi7x7 for pointing out a flaw in my uniformity. I think I've fixed it with shuffling but let me know if there's another problem
EDIT2: Improved byte count plus fixed type restriction
[Answer]
# [Haskell](https://www.haskell.org/), 188 bytes
```
import System.Random
import Data.List
n!s|s>n/2=map(1-)<$>n!(n-s)|1>0=(zipWith(-)=<<tail).sort.map(*s).(++[0,1::Double])<$>mapM(\a->randomIO)[2..n]>>= \a->if all(<=1)a then pure a else n!s
```
Ungolfed:
```
n!s
 |s>n/2       = map (1-) <$> n!(n-s)       --If total more than half the # of numbers, mirror calculation 
 |otherwise   = (zipWith(-)=<<tail)        --Calculate interval lengths between consecutive numbers
              . sort                       --Sort
              . map(*s)                    --Scale
              . (++[0,1::Double])          --Add endpoints
              <$> mapM(\a->randomIO)[2..n] --Calculate n-1 random numbers
              >>= \a->if all(<=1)a then pure a else n!s   --Retry if a number was too large
```
[Try it online!](https://tio.run/##PY9BT4QwEIXv/RXDRpPWlQoYDxDa015MNBp3Ew/LxozZEhpLIbQkYPa/I6y6t3nvTb55U6H7UsZMum6bzsNODZ6/dtr68t/ajs6rmr@hPTY1@TM36JE/aeeJDdzJSXuXiBpbGocsv5I2oDZ07BTLSNBv3b5rX9GQiTz3qA3jbkbwZf3GMU7X6310G2fZpuk/jTosgDl7pgWGsjtffXxh@4Rze5BSwGLrEtAYmouYIfhKWWj7TgGCMk7BXGnyynkYYAQBx4bMSR7CEIwEFvQHtMuLgOR3KGG1azyaDK7LwhZ2BdT1NSAjNWo7I860OIIHkPIioou4h4SnaTr9AA "Haskell – Try It Online")
]