g | x | w | all
Bytes Lang Time Link
053Janet250507T211648Zxigoi
nanPerl 5180123T223427ZXcali
049Juby250507T153220ZJordan
004Thunno 2230726T110613ZThe Thon
005Vyxal r210728T032914Zemanresu
051R180207T195445Zrturnbul
008Pyt180206T184616Zmudkip20
006Japt180123T172653ZShaggy
016K4180123T194842Zmkst
059AWK180123T161123ZRobert B
048PHP170126T182816ZTitus
050Haskell160526T011748ZMichael
087C#160601T180650Zraive
063Clojure160526T162832Zmark
015J160527T091625ZZgarb
027Julia160525T041307ZDennis
014Dyalog APL160525T232019ZAdá
072Swift160526T123741ZJohn McD
090Java160525T090241ZShaun Wi
022J160526T033840Zljeabmre
008Jelly160525T231104ZAdá
010Jolf160525T182430ZConor O&
032Perl 6160525T163405ZBrad Gil
011CJam160525T073222ZLuis Men
054Perl 5.10160525T113509ZSake
064PowerShell v2+160525T125804ZAdmBorkB
008Pyke160525T125322ZBlue
026Vitsy160525T110301ZAddison
006Pyth160525T020051ZMaltysen
028Mathematica160525T103158ZMartin E
010Jelly160525T093328Zjimmy230
00705AB1E160525T083726ZEmigna
007Actually160525T053119Zuser4594
015J160525T035055ZLeaky Nu
032JavaScript ES7160525T080250ZNeil
071Hoon160525T050841ZRenderSe
009MATL160525T045821Zbeaker
009MATL160525T033555ZSuever
006Jelly160525T032711ZLeaky Nu
034Ruby160525T024107ZValue In
028Julia160525T032638ZSp3000
043Python 3160525T031509ZSp3000
055JavaScript ES5160525T030626ZDowngoat
029Octave160525T024053Zbeaker
046Python 3160525T022120ZKeatinge
023Minkolang 0.15160525T025129ZEl'e

Janet, 53 bytes

|(/(+;(seq[k :down[$ 0]](math/ceil(math/log2 k)))1)$)                                                                                   

\$\displaystyle a_n = \frac{1 + \sum_{k=1}^n \left\lceil \log_2 k \right\rceil}{n}\$

Perl 5, 39 + 1 (-p) = 40 bytes

map$b+=0|(log)/log 2,2..$_-1;$_=$b/$_+1

Try it online!

Perl 5, 44 43 + 2 (-pa) = 45 bytes

-1 thanks to @DomHastings

$\+=(length sprintf'%b',$_)/"@F"while$_--}{

Try it online!

J-uby, 49 bytes

:*|:*&(~:to_s&2|:+@)|~:^%(:+@|:& &~:fdiv|:|&:sum)

Attempt This Online!

Thunno 2, 4 bytes

Lḃḷm

Try it online!

Explanation

Lḃḷm  # Implicit input
L     # Push [0..input)
 ḃ    # Convert each to binary
  ḷ   # And get the length of each one
   m  # Take the average of the result
      # Implicit output

Vyxal r, 5 bytes

ʁbfL/

Try it Online!

ʁ     # 0...a
 b    # Turn each into base 2
  f   # Flatten
   L  # Get the length
    / # Divide by the input

R, 51 bytes

Takes input from stdin. Uses the OEIS formula and then divides by n.

(2+ceiling(log2(n<-scan()))*n-2^ceiling(log2(n)))/n

Try it online!

Pyt, 8 bytes

⁻řļ⌊⁺Á1µ

Explanation:

                Implicit input (N)
⁻               Decrement by 1 (N-1)
 ř              Push [1,2,...,N-1]
  ļ             element-wise log base 2 of [1,2,...,N-1]
   ⌊⁺           element-wise floor and increment
     Á          Push contents of array onto stack
      1         Push 1
       µ        Get mean of stack
                Implicit output

Try it online!

Japt, 6 bytes

o¤xÊ/U

Try it


Explanation

           :Implicit input of integer U
o          :Range [0,U)
 ¤         :Convert each to a base-2 string
   Ê       :Get length of each
  x        :Reduce by addition
    /U     :Divide by U
           :Implicit output of result

K4, 16 bytes

Solution:

(1+#,/2\:'!x)%x:

Example:

(1+#,/2\:'!x)%x:5
1.8
(1+#,/2\:'!x)%x:6
2f
(1+#,/2\:'!x)%x:7
2.142857

Explanation:

Convert each number to binary, sum up the bits, add 1 for 0, divide by input.

(1+#,/2\:'!x)%x: / the solution
              x: / store input as x
(           )%   / divide left by right
          !x     / range 0..x-1
      2\:'       / convert each (') to bits (2\:)
    ,/           / flatten result
   #             / count length of list
 1+              / add one (as 0 contains 0 bits!)

Extra:

Precision is determined by the P system setting. Default is 7, max is 17

\P 7
(1+#,/2\:'!x)%x:7
2.142857

\P 12
(1+#,/2\:'!x)%x:7
2.14285714286

\P 17
(1+#,/2\:'!x)%x:7
2.1428571428571428

AWK, 59 bytes

{for(s=1;++n<$0;s+=int(log(n*2)/log(2)));printf"%.8g",s/$0}

Since AWK only does base-10 logs, I had to convert to base-2 and I chose to multiply the argument by 2 rather than add 1 to the result. It's the same byte-count, but I like it. :)

Try it online!

PHP, 48 bytes

a direct port of Sp3000´s answer

<?=(2-2**$x=strlen(decbin($n=$argv[1]))-2)/$n+$x

Haskell, 50 bytes

r x|x<1=0|1<2=1+r(x/2)
f n=(sum(r<$>[0..n-1])+1)/n

C#, 87 bytes

double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}

I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.

Clojure, 71 64 63 bytes

It looks like ratios are ok according to Which number formats are acceptable in output?

(fn[n](/(inc(apply +(map #(.bitLength(bigint %))(range n))))n))

ungolfed (and slightly rewritten for ease of explanation)

(fn [n]
 (->
  (->>
   (range n)                      ;;Get numbers from 0 to N
   (map #(.bitLength (bigint %))) ;;Cast numbers to BigInt so bitLength can be used
   (apply +)                      ;;Sum the results of the mapping
   (inc))                         ;;Increment by 1 since bitLength of 0 is 0
  (/ n)))                         ;;Divide the sum by N

old answer that used (float):

(fn[n](float(/(inc(apply +(map #(..(bigint %)bitLength)(range n))))n)))

output is like:

J, 15 bytes

%~[:+/#@#:"0@i.

This is a monadic verb, used as follows:

   f =: %~[:+/#@#:"0@i.
   f 7
2.14286

Try it here!

Explanation

I implemented the challenge spec pretty literally. There are other approaches, but all turned out to be longer.

%~[:+/#@#:"0@i.  Input is y
             i.  Range from 0 to y-1.
          "0@    For each number in this range:
      #@           Compute the length of
        #:         its base-2 representation.
  [:+/           Take the sum of the lengths, and
%~               divide by y.

Julia, 27 bytes

n->endof(prod(bin,0:n-1))/n

Try it online!

How it works

Since * is string concatenation in Julia, prod can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so prod(bin,0:n-1) is the string of the binary representation of all integers in the desired range. Taking the length with endof and dividing by n yields the mean.

Dyalog APL, 14 bytes

(+/1⌈(⌈2⍟⍳))÷⊢

range ← ⍳
log   ← ⍟
log2  ← 2 log range
ceil  ← ⌈
bits  ← ceil log2
max   ← ⌈
fix0  ← 1 max bits
sum   ← +/
total ← sum fix0
self  ← ⊢
div   ← ÷
mean  ← sum div self

Swift, 72 bytes

func f(n:Double)->Double{return n<1 ?1:f(n-1)+1+floor(log2(n))}
f(N-1)/N

Java, 135 95 90 bytes

float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}

J, 22 bytes

[:(+/%#)[:([:##:)"0 i. Usage:

    bin =: [:(+/%#)[:([:##:)"0 i.
    bin 7
2.14286

Jelly, 8 bytes

Not shorter, but interesting algorithm, and my first Jelly submission:

Rl2Ċ»1S÷

R         1 to n
 l2       log2
   Ċ      ceiling
    »1    max of 1 and...
      S   sum
       ÷  divided by n

Jolf, 10 bytes

/uΜr0xdlBH

Try it here!

Explanation

/uΜr0xdlBH
  Μr0x      map range 0..x
      dlBH  over lengths of binary elements
/u          divide sum of this
            by implicit input (x)

Perl 6,  34  32 bytes

{$_ R/[+] map *.base(2).chars,^$_}

{$_ R/[+] map {(.msb||0)+1},^$_}

Explanation:

{ 
  $_  # the input
  R/  # divides ( 「$a R/ $b」 is the same as 「$b / $a」 )
  [+] # the sum of:
  map
    {
      (
       .msb # the most significant digit (0 based)
       || 0 # which returns Nil for 「0.msb」 so use 0 instead
            # should be 「(.msb//0)」 but the highlighting gets it wrong
            # it still works because it has the same end result 
      ) 
      + 1   # make it 1 based
    },
    ^$_ # 「0 ..^ $_」 all the numbers up to the input, excluding the input
}

Test:

use v6.c;

# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}

for 1..7 {
  say .&mean-bits
}

say '';

say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);
1
1
1.333333
1.5
1.8
2
2.142857

<15/7>
(2. 142857)

CJam, 13 12 11 bytes

One byte saved thanks to @Sp3000, and another thanks to @jimmy23013

rd_,2fbs,\/

Try it online!

Explanation

Straightforward. Applies the definition.

rd      e# read input and convert to double 
_       e# duplicate 
,       e# range from 0 to input minus 1
2fb     e# convert each element of the array to binary 
s       e# convert to string. This flattens the array
,       e# length of array 
\       e# swap 
/       e# divide 

Perl 5.10, 54 bytes

for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u

Pretty much straightforward. sprintf"%b" is a neat way to output a number in binary in Perl without using additional libraries.

Try it online!

PowerShell v2+, 64 bytes

param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n

Very straightforward implementation of the spec. Loops from 0 to $n-1 with |%{...}. Each iteration, we [convert] our input number $_ to a string base2 and take its length. We accumulate that in $o. After the loops, we simply divide $o/$n, leaving that on the pipeline, and output is implicit.

As long as this is, it's actually shorter than the formula that Sp & others are using, since [math]::Ceiling() and [math]::Log() are ridiculously wordy. Base conversion in PowerShell is yucky.

Pyke, 8 bytes

Qmb2slQ/

Try it here!

Vitsy, 26 bytes

This is a first attempt, I'll golf this down more and add an explanation later.

0vVV1HV1-\[2L_1+v+v]v1+V/N

Try it online!

Pyth, 6 bytes

.Oml.B

Try it online here.

.Oml.BdUQ              Filling in implict vars

.O                     Average of list
 m   UQ                Map over [0..input)
  l                    Length of
   .B                  Binary string representation of int
    d                  Lambda var

Mathematica, 28 bytes

(Tr@⌈Log2@Range@#⌉+1)/#&

or

Tr@⌈Log2@Range@#⌉/#+1/#&

In either case, it's an unnamed function which takes N as an input and returns an exact (rational) result for the mean.

Jelly, 10 bytes

BL©2*2_÷+®

From Sp3000's suggestion.

Try it here.

Jelly, 11 bytes

æḟ2’Ḥ÷_BL$N

Not very short but I need some tips.

Try it here.

Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)

05AB1E, 9 7 bytes

Code:

L<bJg¹/

Explanation:

L<         # range from 0..input-1
  b        # convert numbers to binary
   J       # join list of binary numbers into a string
    g      # get length of string (number of bits)
     ¹/    # divide by input

Try it online

Edit: saved 2 bytes thanks to @Adnan

Actually, 7 bytes:

;r♂├Σl/

Try it online!

Explanation:

;r♂├Σl/
;        duplicate input
 r       push range(0, n) ([0, n-1])
  ♂├     map binary representation
    Σ    sum (concatenate strings)
     l/  divide length of string (total # of bits) by n

If it weren't for a bug that I just discovered, this solution would work for 6 bytes:

r♂├♂læ

æ is the builtin mean command.

J, 21 17 15 bytes

From 17 bytes to 15 bytes thanks to @Dennis.

+/@:%~#@#:"0@i.

Can anyone help me golf this?...

Ungolfed version

range        =: i.
length       =: #
binary       =: #:
sum          =: +/
divide       =: %
itself       =: ~
of           =: @
ofall        =: @:
binarylength =: length of binary "0
average      =: sum ofall divide itself
f            =: average binarylength of range

JavaScript (ES7), 38 32 bytes

n=>(l=-~Math.log2(n))-(2**l-2)/n

Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes:

n=>(l=-~Math.log2(n))-((1<<l)-2)/n

Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get:

                                11111111111111111111111
                111111111111111100000000000000001111111
        11111111000000001111111100000000111111110000000
    111100001111000011110000111100001111000011110000111
  11001100110011001100110011001100110011001100110011001
0101010101010101010101010101010101010101010101010101010

The size of this rectangle is nl so the average is just l but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l - 2.

Hoon, 71 bytes

|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq

...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.

Create a function that takes an atom, r. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with ++add. Convert both the output of the fold and r to @rq (quad-precision floating point numbers) with ++sun:rq, and then divide one by the other.

The oddest thing in this snippet is the :.^rq at the end. a:b in Hoon means "evaluate a in the context of b". ++rq is the core that contains the entire quad-precision implementation, like a library. So running (sun 5):rq is the same thing as doing (sun:rq 5).

Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm ++rq to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with only the arms defined in ++rq. Unluckily, rq redefines ++add to be floating-point add instead, along with not having r in its context. . (the entire current context) does, however.

When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of a:[. rq] it would look in the entire current context for a before moving on to looking in rq. So add will look up the function that works on atoms instead of floating-point numbers...but so will div. Hoon also has a feature where using ^name will ignore the first found reference, and look for the second.

From there, it's simply using the syntatic sugar of a^b being equal to [a b] to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of ++div:rq.

> %.  7
  |=
  r/@
  (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428

MATL, 9 bytes

:qBYszQG/

Try it online!

Explanation

:qBYszQG/
:               % take vector [1..n]
 q              % decrement by 1 to get [0..n-1]
  B             % convert from decimal to binary
   Ys           % cumulative sum (fills in 0's after first 1)
     z          % number of nonzero elements
      Q         % increment by 1 to account for zero
       G        % paste original input (n)
        /       % divide for the mean

MATL, 9 bytes

q:ZlksG/Q

Try it Online!

Modified version with all test cases

Explanation

    % Implicitly grab input (N)
q:  % Create array from 1:N-1
Zl  % Compute log2 for each element of the array
k   % Round down to the nearest integer
s   % Sum all values in the array
G   % Explicitly grab input again
/   % Divide by the input
Q   % Add 1 to account for 0 in [0, ... N - 1]
    % Implicitly display the result

Jelly, 6 bytes

R’BFL÷

Try it online!

R’BFL÷  Main monadic chain. Argument: n

R       yield [1, 2, ..., n]
 ’      decrement; yield [0, 1, ..., n-1]
  B     convert to binary; yield [[0], [1], [1,0], [1,1], ...]
   F    flatten list; yield [0, 1, 1, 0, 1, 1, ...]
    L   length of list
     ÷  divide [by n]

Ruby, 44 34 bytes

Now starring the formula used by @Sp3000

->x{(2.0-2**b=x.to_s(2).size)/x+b}

Old version:

->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}

Julia, 28 bytes

n->mean(ceil(log2([2;2:n])))

Since bin doesn't automatically map over arrays, we're using ceil(log2(n)) to get the number of bits in n-1. This works out nicely because Julia's a:b notation is inclusive on both ends, so 2:n is a range from 2 to n, but we're really calculating the number of bits for numbers in the range 1:n-1. Unfortunately though, we need to tack on an extra 2 to account for 0.

Try it online!

Python 3, 43 bytes

def f(n):x=len(bin(n))-2;return(2-2**x)/n+x

Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to x.

Alternative approach for 46 bytes:

lambda n:-~sum(map(int.bit_length,range(n)))/n

Unfortunately, the -~ is necessary since (0).bit_length() is 0, but even then it'd be a byte too long.

JavaScript ES5, 55 bytes

n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)

Explanation

n =>   // anonymous function w/ arg `n`
  for( // loop
      o=0,  // initalize bit counter to zero
      p=n   // copy the input
    ;n-- // will decrease input every iteration, will decrease until it's zero
    ;o+=    // add to the bitcounter
        n.toString(2)  // the binary representation of the current itearations's
                     .length // length
        /p   // divided by input copy (to avergage)
   );o       // return o variable  

Octave, 29 bytes

@(n)1+sum(fix(log2(1:n-1)))/n

Explanation

              log2(1:n-1)       % log2 of numbers in range [1..n-1]
                                % why no 0? because log2(0) = -Inf  :/
          fix(           )      % floor (more or less, for positive numbers)
      sum(                )     % sum... wait, didn't we miss a +1 somewhere?
                                % and what about that missing 0?
                           /n   % divide by n for the mean
    1+                          % and add (1/n) for each of the n bit lengths 
                                % (including 0!)

Sample run on ideone.

Python 3, 46 Bytes

lambda x:sum(len(bin(i))-2for i in range(x))/x

Call it like

f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0

I had to revert the map revision because it failed for input of 5

Minkolang 0.15, 23 bytes

n$z1z[i1+2l$M$Y+]kz$:N.

Try it here!

Explanation

n$z                       Take number from input and store it in register (n)
   1                      Push 1 onto the stack
    z[                    For loop that repeats n times
      i1+                 Loop counter + 1
         2l$M             log_2
             $Y           Ceiling
               +          Add top two elements of stack
                ]         Close for loop
                 z$:      Float divide by n
                    N.    Output as number and stop.

Pretty straightfoward implementation.