Find the geometric mean of n! Using Python

Introduction

I am a beginner who is currently studying Rails on my own. As a hobby, I use Python for numerical calculations. This time, when $ n $ is infinite, the geometric mean of $ n! $, That is,

\lim_{n \to \infty} \frac{\sqrt[n]{n!}}{n}\\

I would like to somehow ask for it in Python.

What is the geometric mean?

Speaking of the average, you can think of the ** arithmetic mean **, which is the sum of all $ n $ data $ x_1, x_2, ..., x_n $ and divided by $ n $. On the other hand, the geometric mean $ \ mu $ is

\mu = \sqrt[n]{x_1x_2...x_n}\\

You can find it at. It is often used to calculate growth rates and interest rates.

Main subject

Now, let's find the geometric mean of n! Shown above. Using the above formula, it can be calculated by $ \ sqrt [n] {n!} $, But it seems that it will not converge when it is skipped to infinity, so consider the case where the one divided by $ n $ is skipped to infinity. .. In other words, find out what percentage of the total $ \ mu $ is. Therefore

\lim_{n \to \infty} \frac{\sqrt[n]{n!}}{n}\\

I will ask for.

Try to solve

First of all, I would like to plot a graph using matplotlib to see which value is likely to converge by trying to change the number to $ n $. With sympy, you can easily calculate even $ 2000! $. If you use the standard module math, you will get an error if the number of digits is too large.

plot.py


import matplotlib.pyplot as plt
import sympy

def fun(n):
    n1 = sympy.factorial(n)
    n2 = n1 ** (1/n)
    n3 = n2/n
    return n3

x = list(range(1,2000,10))
y = []
for i in x:
    y.append(fun(i))

print(x)
print(y)
plt.plot(x,y)
plt.ylim([0.36,0.4])

plot.jpg

Looking at the graph, I feel that it seems to converge around 0.37. Now suppose the above equation converges to some value $ a $. Also, it is difficult to solve with the above formula, so if you take the logarithm,

\log \lim_{n \to \infty} \frac{\sqrt[n]{n!}}{n} = \log a\\
\lim_{n \to \infty} \log \frac{\sqrt[n]{n!}}{n} = \log a\\

To organize,

\begin{align}
\lim_{n \to \infty} \log \frac{\sqrt[n]{n!}}{n} &= \lim_{n \to \infty} (\log {\sqrt[n]{n!}}-\log {n})\\
&= \lim_{n \to \infty} \Bigl( \frac{1}{n}\log {n!}-\log {n}\Bigr)\\
&= \lim_{n \to \infty} \Bigl( \frac{1}{n}\sum_{k=1}^{n} \log k-\log {n}\Bigr)
\end{align}\\

here

\sum_{k=1}^{n} \log k

I will think about. It can be expected that the Squeeze theorem can be used when the limit of the division series comes out. here

\begin{align}
f(x) &= \log({x-1})\\
g(x) &= \log {x}
\end{align}

Introduce. The reason will be shown below. Plot the above three formulas again using matplotlib.

plot2.py


with np.errstate(invalid='ignore'):
    x = np.arange(-1, 11, 0.01)
    y1 = np.log(x)
    y2 = np.log(x-1)
    fig = plt.figure()
    plt.xlim([-1, 11])
    plt.ylim([-2, 4])
    plt.xlabel('x')
    plt.ylabel('y', rotation=0)
    plt.gca().set_aspect('equal')
    plt.grid()
    plt.plot(x, y1, label="g(x)")
    plt.plot(x, y2, label="f(x)", color="green")

    x = list(range(1,11,1))
    y3 = []
    for i in x:
        y3.append(np.log(i))

    print(y3)
    plt.bar(x, y3, width = 1.0, align="edge",color="orange", edgecolor="black", label="Σlogk")
    plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=0, fontsize=8)
    plt.show()
    fig.savefig("log.jpg ")

log.jpg

As you can see from the plot, $ \ sum_ {k = 1} ^ {n} \ log k $ is between the integrals of $ f (x) $ and $ g (x) $. Therefore,

 \int_{2}^{n}\log({x-1})dx< \sum_{k=1}^{n} \log k < \int_{2}^{n}\log {x} dx\\

The definite integral of the above logarithmic function can be solved by using integration by parts. But here the purpose is to use Python, so

integral.py


import sympy as sym
from sympy.plotting import plot
sym.init_printing(use_unicode=True)
from sympy import log

n, x, y = sym.symbols("n x y")
logx1  = log(x)
logx2  = log(x-1)
q1 = sym.integrate(logx1, (x, 2, n+1))
q2 = sym.integrate(logx2, (x, 2, n+1))
print(q1)
print(q2)
-n + (n + 1)*log(n + 1) - 2*log(2) + 1 #log(x)Definite integral solution
-n + (n + 1)*log(n) - log(n) + 1 #log(x-1)Definite integral solution

Then divide each by $ n $ and subtract $ \ log {n} $. In other words, fix it to the first formula.

 \frac{1}{n}-1< \frac{1}{n}\sum_{k=1}^{n} \log k-\log {n} < \log \Bigl(1+\frac{1}{n}\Bigr)+\frac{1}{n}\log(n+1)+\frac{1}{n}-\frac{2}{n}\log2\\

The limit is also found using sympy.

integral.py


import sympy as sym
from sympy.plotting import plot
sym.init_printing(use_unicode=True)
from sympy import log

n, x, y = sym.symbols("n x y")
logx1  = log(x)
logx2  = log(x-1)
q1 = sym.integrate(logx1, (x, 2, n+1))
q2 = sym.integrate(logx2, (x, 2, n+1))
q11 = q1/n-log(n)
q22 = q2/n-log(n)

oo = sympy.oo
lim_q11 = sym.limit(q11, n, oo)
lim_q22 = sym.limit(q22, n, oo)
print(lim_q11)
print(lim_q22)
-1
-1

Therefore, from Squeeze theorem

\lim_{n \to \infty} \Bigl( \frac{1}{n}\sum_{k=1}^{n} \log k-\log {n}\Bigr)=\lim_{n \to \infty} \log \frac{\sqrt[n]{n!}}{n} = -1
\\

By the way, I set the convergence value to $ a $.

\lim_{n \to \infty} \log \frac{\sqrt[n]{n!}}{n} = \log a\\
\begin{align}
a&= \lim_{n \to \infty} \frac{\sqrt[n]{n!}}{n}\\
&= \frac{1}{e}\\
&= 0.367...
\end{align}\\

Thank you for your hard work. Finally the convergence came out. First, it matches the predicted convergence value by substituting an appropriate number. It is a beautiful solution that gives the natural logarithm $ e $.

Finally

How was it? I solved it using a module for numerical calculation in Python, but I think there is a smarter way to solve it. This problem can also be solved within the scope of high school mathematics. It may be fun to think of another solution.

reference

Understanding integrals in Python Solving "extreme value" related problems in high school mathematics with Python

Recommended Posts

Find the geometric mean of n! Using Python
Find the maximum Python
Find the solution of the nth-order equation in python
Try using the collections module (ChainMap) of python3
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Find out the location of Python class definition files.
Cut a part of the string using a Python slice
Explanation of the concept of regression analysis using Python Part 1
Explanation of the concept of regression analysis using Python Extra 1
Study from the beginning of Python Hour8: Using packages
Towards the retirement of Python2
Find the difference in Python
About the ease of Python
About the features of Python
The Power of Pandas: Python
Find the maximum python (improved)
Find out the apparent width of a string in python
View using the python module of Nifty Cloud mobile backend
Python --Find out number of groups in the regex expression
[Python] I tried collecting data using the API of wikipedia
Find the diameter of the graph by breadth-first search (Python memory)
Find the eigenvalues of a real symmetric matrix in Python
Harmonic mean with Python Harmonic mean (using SciPy)
Find the definition of the value of errno
The story of Python and the story of NaN
Image capture of firefox using python
[Python] Find the second smallest value.
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Removal of haze using Python detailEnhanceFilter
pyenv-change the python version of virtualenv
Find the Levenshtein Distance with python
Change the Python version of Homebrew
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
Implementation of desktop notifications using Python
Try using the Python Cmd module
About the basics list of Python basics
Learn the basics of Python ① Beginners
[Python] I wrote the route of the typhoon on the map using folium
[Python] LINE notification of the latest information using Twitter automatic search
[ffmpeg] After ffmpeg using Python subprocess, The system cannot find the path specified.
Get and set the value of the dropdown menu using Python and Selenium
[Python] A simple function to find the center coordinates of a circle
Get images of great find / 47 sites using Python (Part 2/2: I published the target list on github)
Find the maximum value python (fixed ver)
Find the area of the union of overlapping rectangles
Python: Basics of image recognition using CNN
[Python] Extension using inheritance of matplotlib (NavigationToolbar2TK)
Automatic collection of stock prices using python
About building GUI using TKinter of Python
Change the length of Python csv strings
Try using the Wunderlist API in Python
Check the behavior of destructor in Python
(Bad) practice of using this in Python
[Python3] Understand the basics of Beautiful Soup
Try using the Kraken API in Python
Behind the flyer: Using Docker with Python
Pass the path of the imported python module
How to find out the number of CPUs without using the sar command
The story of making Python an exe