Section 1. Introduction
The study of structure formation constitutes one of
the central pillars of modern cosmology, aiming to explain how the universe
evolved from a nearly homogeneous, hot, and dense state (as evidenced by the
cosmic microwave background, CMB) into a complex web containing galaxies,
clusters, filaments, and cosmic voids. Early efforts focused on understanding
small linear perturbations in density that, over billions of years,
gravitationally collapsed into the cosmic tapestry we observe through deep sky
surveys such as the Sloan Digital Sky Survey (SDSS) and the Dark Energy Survey
(DES). These observations have confirmed the model-a framework in which cold dark matter (CDM) drives
structure formation while dark energy accelerates cosmic expansion-though
various refinements and alternatives continue to be explored (Peebles 1980;
Weinberg 2008).
Section 1.1. Historical Developments
Developments in structure formation theory stretch
back several decades, with early seminal work by James Peebles demonstrating
how primordial density fluctuations grow through gravitational instability in
an expanding universe (Peebles 1980; Peebles 1993). This body of work laid the
foundation for more precise theoretical frameworks incorporating general
relativity, gaugeinvariant perturbation theory, and robust statistical analysis
of large-scale structure (Mukhanov, Feldman, and Brandenberger 1992).
Although the current standard model ( ) provides a remarkably successful description of
largescale structure (LSS), there remain open questions about the nature of
dark matter, the properties of dark energy, and possible modifications to
general relativity on cosmic scales (Riess et al. 1998;Perlmutter et al. 1999;
Planck Collaboration 2018). Recent progress has also been driven by advances in
numerical methods and high-performance computing, enabling large N -body
simulations that can track the evolution of billions of collisionless dark matter
particles. These simulations guide our interpretation of galaxy surveys and
help us constrain cosmological parameters with increasing precision.In this
article, we present a comprehensive review of structure formation. After
describing the physical foundations, including primordial fluctuations, linear
and nonlinear growth of perturbations, and virialization, we discuss standard
tools used in the field-such as the matter power spectrum, correlation
functions, halo models, and sophisticated simulation techniques. We then
highlight observational efforts that provide constraints on structure
formation, including galaxy surveys, weak lensing measurements, and Lyman- forest observations.
Section 1.2. How and Where?
In the methodology section, we derive the main
theoretical equations, step by step, focusing on gauge-invariant perturbation
theory and the Newtonian approximation in an expanding background. Throughout
the text, we include relevant mathematical derivations to elucidate how
structure formation emerges naturally from Einstein's field equations, coupled
to fluid conservation laws, under the assumption of cosmological principle. The
discussion offers an extended critical analysis of the strengths and limitations
of our understanding, tackling issues such as potential tensions in the data
(e.g., the so-called tension, the tension) and the uncertain nature of dark matter.
We close with concluding remarks pointing toward future directions of research
in structure formation before presenting the references used.
Section 2. Methodology
In approaching the theory of structure formation,
it is instructive to demonstrate where the key equations arise. While a full
treatment requires the use of general relativity and gauge-invariant
perturbation theory, one can glean many essential results from the Newtonian
approximation, valid for sub-horizon scales in the late universe. We begin with
a brief derivation of the relevant equations.
Section 2.1. The Background Cosmology
The homogeneous and isotropic background of our
universe is well-described by the Friedmann-Lemaître-Robertson-Walker (FLRW)
metric:
where
is the scale factor,
describes the spatial curvature, and
is the speed of light. The scale factor satisfies
the first Friedmann equation (Weinberg 2008):
where
is the total energy density of the universe,
is the gravitational constant, and
is the cosmological constant. The expansion rate
is given by the Hubble parameter
(3).
Section 2.2. Perturbation Equations in the Newtonian Approximation
In an expanding universe, structure formation
proceeds via the growth of small inhomogeneities. One usually defines a density
contrast
by:
where
is the local matter density, and
is the mean matter density of the universe. If
, then the growth of
can be understood by linearizing the fluid and
Poisson equations in a Newtonian framework. The continuity, Euler, and Poisson
equations for a non-relativistic fluid in the expanding background are:
Euler's equation (neglecting pressure for cold dark matter):
Here,
is the peculiar velocity field, and
is the gravitational potential associated with
density fluctuations on sub-horizon scales. By further assuming the linear
regime (
and
), one can neglect the term . Taking a time derivative of the continuity
equation and substituting into the Euler equation while employing Poisson's
equation yields the well-known linear evolution equation for
:
The general solution of equation (8) is a
superposition of a growing mode and a decaying mode . The growing mode is typically the relevant solution for structure
formation. In an Einstein-de Sitter universe (i.e., matter-dominated, flat, ), . For other cosmological backgrounds, one must
solve equation (8) numerically (Heath 1977). The above derivations highlight how
structure formation emerges naturally in a universe filled with matter
(baryonic and dark) that is allowed to clump under gravity. Coupling these
equations to an initial power spectrum of perturbations (e.g., from inflation)
allows one to predict statistical measures such as the matter power spectrum, , and correlation functions that describe how
matter is distributed on different scales.
Section 2.3. Derivation of Primordial Fluctuations
A crucial ingredient in the theory of structure
formation is the spectrum of primordial fluctuations, usually denoted
or
, where
is the comoving curvature perturbation. In the
context of inflationary cosmology, quantum vacuum fluctuations are stretched to
cosmological scales, generating a nearly scale-invariant distribution of
density perturbations (Guth and Pi 1982; Liddle and Lyth 2000). After
inflation, these modes re-enter the horizon, shaping the seeds of large-scale
structure. The simplest single-field slow-roll inflationary models predict:
where
is the scalar spectral index. The amplitude of
these perturbations is usually quoted at the CMB pivot scale
. Observations by the Planck satellite find
(Planck Collaboration 2018).
Once these primordial perturbations enter the horizon in a matter-dominated or radiation dominated epoch, they evolve according to the linear theory described earlier, ultimately shaping the matter power spectrum
at late times:
where
is the transfer function that encodes how different scales evolve through horizon crossing, radiation-matter equality, and other relevant epochs, while
describes how fluctuations grow with redshift
. The primordial power spectrum
is determined from inflationary theory and calibrated by CMB measurements.
Section 2.4. Numerical Simulations and N-Body Methods
Analytical linear theory accurately describes early-times or large spatial scales, but fails when density perturbations become nonlinear ( ). To understand these late-time dynamics, researchers rely on N -body simulations in which the universe is discretized into "particles" representing collisionsless dark matter. The classical Poisson equation for gravity is solved on a discrete mesh or via tree-based algorithms to evolve the positions and velocities of particles forward in cosmic time (Efstathiou et al. 1985; Springel et al. 2005).
Early landmark simulations, such as the Millennium Simulation (Springel et al. 2005), tracked the evolution of over particles in cubes several hundred megaparsecs on a side. More recent simulations like Illustris (Vogelsberger et al. 2014) and IllustrisTNG (Nelson et al. 2019) include baryonic processes-such as gas cooling, star formation, and feedback from supernovae and active galactic nuclei-by solving fluid equations on adaptive meshes or smoothed-particle hydrodynamics (SPH) codes (Teyssier 2002; Wadsley et al. 2004).Such simulations yield predictions for the distribution of dark matter halos, galaxy clustering, and various higher-order statistics such as bispectra. They also provide theoretical "mock catalogs" used for analyzing large-scale structure surveys. While progress has been remarkable, remaining uncertainties in baryonic physics, numerical resolution, and alternative dark matter scenarios (e.g., warm dark matter, self-interacting dark matter) drive ongoing research. Nevertheless, N -body simulations form a crucial component of the structure formation toolkit.
Section 2.5. Observational Constraints
Our knowledge of structure formation relies critically on comparing theoretical predictions to observations. Galaxy surveys such as the Sloan Digital Sky Survey (York et al. 2000), 2dF Galaxy Redshift Survey (Colless et al. 2001), and more recent efforts by DES, HSC, KiDS, and Euclid measure the three-dimensional positions of millions of galaxies, from which we can infer the matter correlation function, power spectrum, and various clustering statistics. Weak gravitational lensing surveys map the distribution of matter by measuring coherent distortions in the shapes of distant galaxies. The Lyman- forest in quasar spectra probes the matter distribution at high redshifts (Croft et al. 1998). Together, these probes place stringent limits on cosmological parameters, such as , and the sum of neutrino masses (Planck Collaboration 2018). The synergy between different observational windows consistently favors , but significant tensions and open questions remain.
Figure 1.
Graph 1. Dimensionless Matter Power Spectrum and Graph 2. Real-Space Correlation Function.
Figure 1.
Graph 1. Dimensionless Matter Power Spectrum and Graph 2. Real-Space Correlation Function.
Section 2.6. Explanation of the Graphs
Graph 1. Dimensionless Matter Power Spectrum,:
The first graph displays the function
which is often used to indicate the amount of variance (per logarithmic interval in
) contributed by modes of a given wavenumber. Where
, fluctuations at the corresponding
scale are transitioning to the nonlinear regime. At in the standard CDM scenario, nonlinear effects become important around , although the exact scale depends on more rigorous calculations than our simple demonstration code.
Graph 2. Real-Space Correlation Function,:
The second graph shows the two-point correlation function in real space, defined by
This function measures the excess probability (relative to a random distribution) of finding matter pairs at a separation
. For instance, a positive
at a certain scale means that matter is clustered above the random expectation at that distance, while negative
would indicate an anti-correlation at that scale.
In more advanced analyses, one would use high-resolution Boltzmann codes to compute accurately across different epochs, include effects from baryons, neutrinos, and non-trivial dark energy models, and perform numerically stable integrals for . Nonetheless, these demonstrations illustrate two commonly plotted functions that help us interpret the clustering of matter in the universe.
Figure 2. Graph 3. Illustrative Linear Matter Power Spectrum
This graph represents an illustrative linear matter power spectrum, showing the relationship between the wave number (in units of ) and the power spectrum (in arbitrary units). The power spectrum is a key quantity in cosmology that describes how matter is distributed across different spatial scales in the universe.
Key Features:
- 2.
Power Spectrum :
- 3.
Redshift (z):
Different curves correspond to different redshift values . Redshift is a measure of how much the universe has expanded since the light from a structure was emitted. Higher indicates earlier times in the universe.
- 4.
Behavior of the Curves:
For small (large scales), remains nearly constant. This indicates that fluctuations on large scales are relatively unchanging across different redshifts.
For larger (smaller scales), the power spectrum drops sharply. This drop corresponds to the suppression of small-scale fluctuations due to processes such as Silk damping or freestreaming.
- 5.
Impact of Redshift:
Overall Interpretation:
The graph illustrates the general trend of the linear matter power spectrum across scales and its evolution over time (through redshift). On large scales (low), structures are governed primarily by gravitational growth, while on small scales (high), processes such as the pressure of baryonic matter or dark matter dynamics suppress the formation of structures.
Section 3. Discussion
The discussion on structure formation in cosmology is inherently rich and multifaceted, spanning an enormous range of scales, epochs, and physical processes. In this extended section, we delve into the merits (pros) of the standard picture and also highlight a variety of critiques and ongoing puzzles (cons). Although the standard model, complemented by the theory of inflation, has been remarkably successful, it is essential to critically examine its assumptions, domain of applicability, and potential extensions. By structuring this narrative within a fluid text, we aim to present a unifying perspective that does not shy away from the open challenges facing this field.A substantial point in favor of the standard scenario is its ability to account for an enormous range of observations with a surprisingly small set of parameters. When inflationary theory is invoked, the generation of near scale-invariant primordial fluctuations emerges organically from quantum physics under rapidly expanding space-time. These theoretical calculations accurately predict the СМВ angular power spectrum, which exhibits acoustic peaks consistent with baryon-photon oscillations in the early universe (Hu and Sugiyama 1995). The amplitude and shape of these peaks have been measured to exquisite precision by missions such as WMAP (WMAP Collaboration 2009) and Planck (Planck Collaboration 2018). In particular, the standard model makes a convincing link between early-universe physics and present-day structure formation by correctly forecasting the amplitude of matter fluctuations required to seed the formation of galaxies and clusters.One of the most striking accomplishments of this model lies in the robustness of the linear perturbation theory framework, which quantitatively predicts how cosmic overdensities grow during different epochs. Initially, these overdensities remain small, permitting a linear approximation. This approximation holds well until structures reach the scale of galaxy groups or clusters, at which point the nonlinear processes come into play. Even in the nonlinear regime, advanced numerical N -body simulations, performed with large supercomputers, verify that a universe dominated by cold dark matter can reproduce the large-scale distribution of galaxies and the cosmic web. The phenomenon known as "biased galaxy formation"-where galaxies trace underlying dark matter halos in a statistically biased manner-further cements the concordance picture when observed galaxy clustering is compared to dark matter distributions gleaned from simulations (Kaiser 1984; Bardeen et al. 1986).
Furthermore, the synergy of multiple observational probes has consistently reinforced the model. For instance, distant Type la supernovae measurements indicating cosmic acceleration, cosmic shear data from weak lensing surveys, and baryon acoustic oscillations (BAO) from galaxy surveys altogether fit within a single cosmological parameter space that strongly favors and . The high-redshift observations of the Lyman- forest also show that small-scale fluctuations at redshifts around align with predictions once the proper thermal history of the intergalactic medium is accounted for. This coherence across vastly different scales and epochs is one of the model's most substantial triumphs.Despite these successes, certain tensions and open questions stand out, revealing that cosmology is still a dynamic and evolving discipline. One of the most well-known tensions, often referred to as the Hubble tension, concerns the discrepancy between the Hubble constant inferred from local distance ladder measurements (Riess et al. 2019) and that inferred from CMB data under the assumption of (Planck Collaboration 2018). While the latter method suggests , local measurements yield values around . If this discrepancy persists with higher precision, it may indicate physics beyond the standard model, such as interactions within the dark sector, non-standard neutrino physics, or exotic forms of early dark energy.Another tension related to structure formation specifically concerns the amplitude of matter fluctuations, often quantified by , and the parameter . Clustering measurements from weak lensing and redshift-space distortions sometimes yield slightly lower values of or compared to those predicted by Planck data within CDM (Joudaki et al. 2017; Heymans et al. 2021). This discrepancy, known as the or tension, might be explained by systematic uncertainties in lensing measurements or incomplete modeling of baryonic feedback in simulations, but it might also point to interesting modifications in the growth of structure.Additionally, while cold dark matter is highly favored for explaining both cosmic microwave background power spectra and large-scale structure, it is not without its own challenges. On small galactic scales, longstanding issues such as the "core-cusp problem," the "missing satellites problem," and the "too-big-to-fail problem" linger (Bullock and Boylan-Kolchin 2017). These may be resolved by baryonic feedback mechanisms, or they may hint at alternative dark matter scenarios, such as self-interacting dark matter, warm dark matter, or fuzzy dark matter. Each scenario has distinct predictions for structure formation at small scales, particularly regarding subhalo abundance and internal halo density profiles.
Section 3.1. A further Realm of Theoretical Speculation
Science ca not still pro whether the law of gravity itself might require modification on large scales. Extensions to general relativity, commonly categorized under "modified gravity" theories, sometimes aim to explain cosmic acceleration without invoking a cosmological constant. These theories, however, must also consistently predict large-scale structure. Observables such as the growth rate of density perturbations, parameterized by , the integrated Sachs-Wolfe effect, and gravitational lensing patterns, offer powerful constraints. While most modified gravity theories have been severely restricted by the data, the very existence of cosmic acceleration spurs ongoing exploration of gravity's behavior at large distances, even if remains the leading model.
Even if one accepts the standard gravitational framework, the precise nature of dark energy remains unexplored beyond the fact that it behaves almost exactly like a cosmological constant on cosmic scales. If the dark energy density does evolve over time, it could alter the growth of structure, especially at late times. Upcoming surveys such as the Vera C. Rubin Observatory's Legacy Survey of Space and Time (LSST), the Euclid mission, and the Nancy Grace Roman Space Telescope promise improved measurements of both expansion history and structure growth, potentially illuminating the dark energy sector.
Section 3.2. Methodological Breakthroughs
One should also acknowledge the methodological breakthroughs required to address some of these open questions, particularly regarding the interplay of astrophysical processes on smaller, nonlinear scales. Baryonic physics, including star formation, supernova feedback, and black hole accretion, can significantly affect the distribution of matter, especially at galaxy and cluster scales, by heating the surrounding gas and expelling it from halos, thus flattening the central density profiles. Accurately modeling these processes within large cosmological volumes demands advanced numerical techniques, sub-grid models, and more refined observational data to calibrate them. Discrepancies between different hydrodynamic codes-for instance, those employing smoothed-particle hydrodynamics versus adaptive mesh refinement-highlight the difficulties in robustly predicting baryonic effects on the matter power spectrum. In addition, phenomena such as cosmic reionization at high redshifts further complicate the modeling, linking large-scale structure with cosmic dawn and the formation of the first luminous objects.
Despite these many potential pitfalls, the general agreement of predictions with a wide range of data sets remains profoundly compelling. From the horizon-scale signatures in the CMB to the arrangement of galaxies and clusters in the local universe, the scenario of gravitational instability seeded by primordial quantum fluctuations consistently passes the test. Therefore, while caution dictates that we remain open to paradigmatic shifts if tensions worsen, the track record of successful predictions undeniably places at the forefront.
Moreover, the theoretical elegance of inflation as a mechanism for generating these primordial seeds cannot be overstated. It explains not only the amplitude and shape of the primordial power spectrum but also the overall flat geometry observed in the universe. Nonetheless, inflation is not a single theory but rather a framework that hosts a multitude of models, some of which predict distinctive secondary features (such as primordial non-Gaussianities, gravitational waves, or isocurvature modes). The continuing absence of a decisive detection of primordial B-mode polarization, for instance, imposes strong constraints on the energy scale of inflation. Equally, any future detection of a primordial gravitational wave background would be groundbreaking, shedding light on the scale at which inflation might have occurred.
Section 3.3. Summary
In summary, the "pros" of the standard picture are formidable: the generation of scale-invariant spectra from inflation, a matter-dominated regime that fosters gravitational instability, dark matter that clumps efficiently, and a late-time dark energy component that explains accelerated expansion. These yield coherent, parameter-light explanations for a deluge of observational data, from the CMB to the distribution of galaxies and clusters. The "cons" or challenges-manifesting as tensions in measured parameters, uncertainties in small-scale structure, theoretical ambiguities regarding inflation's specifics, the puzzling nature of dark energy-serve not to undermine the model's efficacy but to remind us that cosmology remains a vibrant field at the intersection of particle physics, astrophysics, and gravitational theory. The goal is not merely to confirm existing paradigms but to discover avenues where new physics may be lurking, waiting to reveal itself in subtle observational signatures or deeper theoretical insights. As experiments and surveys continue to push boundaries, we can expect the story of structure formation to become even richer, offering fresh perspectives on some of the most fundamental questions concerning our universe.
Altogether, the theory and observation of structure formation stands among the crowning achievements of contemporary science, weaving together advanced mathematics, high-performance computing, and extraordinary observational data into a tapestry that encapsulates cosmic history. While significant progress has been made, the field is far from complete, and the ongoing interactions of theory and observation will likely yield further revelations in the years to come.
Section 5. Attachments
Python Codes:
Graph 1 and 2:
import numpy as np
import matplotlib.pyplot as plt
# In this illustrative Python code, we will demonstrate the generation
# of a simplified linear matter power spectrum P(k) for different redshifts
# in a standard cosmology. This example is for didactic purposes and does
# not represent a rigorous calculation with a Boltzmann code such as CAMB
# or CLASS.
# We'll assume a simple transfer function and growth factor, ignoring
# baryonic effects, neutrinos, etc.
# Define array of wavenumbers in h/Mpc (log-spaced for convenience).
k_vals = np.logspace(-3, 1, 100)
# Define some cosmological parameters
Omega_m = 0.3
Omega_lambda = 0.7
h = 0.7
sigma8 = 0.8
n_s = 0.96
# Primordial power spectrum amplitude (arbitrary normalization in this example)
A_s = sigma8**2
# A simple approximation of the linear transfer function T(k) (not physically rigorous!)
def transfer_function(k):
# A naive approximation that saturates at small k and decays at large k
return np.exp(- (k/0.2)**2 )
# Define a simple growth factor for matter-dominated epoch (ignoring acceleration)
def growth_factor(z):
# Rough EdS behavior: D+(a) ~ a, with a = 1/(1+z)
# This is a crude approximation ignoring Lambda, for demonstration only.
a = 1.0 / (1.0 + z)
return a
# Let's compute the matter power spectrum P(k,z) ~ k^n_s * T(k)^2 * [D+(z)]^2
def matter_power_spectrum(k, z):
return A_s * k**n_s * transfer_function(k)**2 * growth_factor(z)**2
# For demonstration, we choose some redshifts
redshifts = [0, 1, 2, 4]
plt.figure(figsize=(8,6))
for z in redshifts:
pk = [matter_power_spectrum(kv, z) for kv in k_vals]
plt.loglog(k_vals, pk, label=f"z={z}")
plt.xlabel(r"$k \, [h/\mathrm{Mpc}]$")
plt.ylabel(r"$P(k) \, [\mathrm{(arbitrary\,units)}]$")
plt.title("Illustrative Linear Matter Power Spectrum")
plt.legend()
plt.grid(True)
plt.show()
The Python code above offers a simplified illustration of how one might compute and plot a linear matter power spectrum for different redshifts. In actual cosmological research, codes such as CAMB or CLASS solve a set of Boltzmann equations to compute a more accurate transfer function, taking into account the detailed physics of photons, neutrinos, baryons, and dark matter. Moreover, the growth factor in a ΛCDM universe deviates from the simple matter-dominated ∝a\propto a∝a dependence used here, thus requiring full integration of the linear perturbation equation (7) in the presence of a cosmological constant.
Overall, the code demonstrates how theoretical predictions of structure formation at various redshifts can be generated and visualized, representing a fundamental step before comparing these predictions to real data obtained from galaxy surveys or lensing measurements.
Graph 3.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import simps
# ========== Cosmological and Numerical Parameters ==========
Omega_m = 0.3
Omega_lambda = 0.7
h = 0.7
sigma8 = 0.8
n_s = 0.96
# A simple amplitude for the primordial spectrum (arbitrary normalization)
A_s = sigma8**2
# Define array of wavenumbers in h/Mpc (log-spaced for convenience).
k_vals = np.logspace(-3, 1, 200)
# ========== Simplified Transfer Function ==========
def transfer_function(k):
"""
A naive approximation of the transfer function that
saturates at low k and decays at high k. Not physically rigorous,
used for illustration only.
"""
return np.exp(-(k/0.2)**2)
# ========== Growth Factor (rough matter-dominated approximation) ==========
def growth_factor(z):
"""
For demonstration, we'll use the approximate EdS growth factor D+(a) ~ a,
ignoring Lambda for simplicity. In reality, one should solve the full
growth equation in a Lambda-CDM background.
"""
a = 1.0 / (1.0 + z)
return a
# ========== Matter Power Spectrum P(k,z) ==========
def matter_power_spectrum(k, z=0):
"""
Compute P(k,z) ~ A_s * k^n_s * T^2(k) * D+(z)^2
(with an arbitrary amplitude for demonstration).
"""
return A_s * k**n_s * transfer_function(k)**2 * growth_factor(z)**2
# ========== 1) Dimensionless Matter Power Spectrum, Delta^2(k) = k^3 * P(k) / 2pi^2 ==========
# We'll fix z = 0 for illustration.
z_plot = 0
pk_vals = matter_power_spectrum(k_vals, z=z_plot)
# Dimensionless power spectrum:
delta_sq_vals = (k_vals**3) * pk_vals / (2.0 * np.pi**2)
# ========== 2) Real-Space Correlation Function, xi(r) ==========
# The real-space correlation function is defined as:
# xi(r) = 1/(2*pi^2) * \int_0^\infty k^2 P(k) sin(k*r)/(k*r) dk
#
# We'll compute xi(r) at several distances r using a discrete integral.
def xi_of_r(r, k_array, pk_array):
"""
Compute the correlation function xi(r) = 1/(2*pi^2)
* integral[ k^2 * P(k) * sin(k*r)/(k*r) dk ],
using a simple numerical integration with sin(k*r)/(k*r).
"""
# Sinc function argument
kr = k_array * r
integrand = k_array**2 * pk_array * np.sin(kr) / kr
# Integrate using Simpson's rule over log-spaced k
return (1.0 / (2.0 * np.pi**2)) * simps(integrand, k_array)
# We'll define an array of radii (in Mpc/h) on which to compute xi(r).
r_vals = np.logspace(-1, 1.5, 100) # e.g., from 0.1 to ~ 31.6 Mpc/h
xi_vals = []
for r in r_vals:
xi_vals.append(xi_of_r(r, k_vals, pk_vals))
# ========== Plotting the Two Graphs ==========
plt.figure(figsize=(12, 5))
# --- Plot 1: Dimensionless Power Spectrum Delta^2(k) ---
plt.subplot(1, 2, 1)
plt.loglog(k_vals, delta_sq_vals, color='blue', label=r'$\Delta^2(k)$')
plt.xlabel(r'$k \, [h/\mathrm{Mpc}]$')
plt.ylabel(r'$\Delta^2(k) = \frac{k^3 P(k)}{2\pi^2}$')
plt.title('Dimensionless Matter Power Spectrum at z={}'.format(z_plot))
plt.grid(True)
plt.legend()
# --- Plot 2: Correlation Function xi(r) ---
plt.subplot(1, 2, 2)
plt.loglog(r_vals, xi_vals, color='red', label=r'$\xi(r)$')
plt.xlabel(r'$r \, [\mathrm{Mpc}/h]$')
plt.ylabel(r'$\xi(r)$')
plt.title('Real-Space Correlation Function at z={}'.format(z_plot))
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()