← 返回资讯屏轩教育 · 行业资讯

Simulating Double Slit Interference: A Computational Approach | 模拟双缝干涉:一种计算方法

2026-08-03 01:36 · 本文部分内容由AI辅助创作

📚 Simulating Double Slit Interference: A Computational Approach | 模拟双缝干涉:一种计算方法

The double slit interference experiment is one of the most iconic demonstrations of wave behaviour, revealing how coherent light produces alternating bright and dark fringes on a screen. From a computer science perspective, simulating this phenomenon offers an excellent opportunity to apply computational thinking, numerical methods and visualisation techniques. By modelling the superposition of waves, discretising continuous domains and rendering the resulting intensity patterns, students can deepen their understanding of both physics and algorithms. This article explores the steps involved in building a robust digital model of double slit interference using a modern programming environment, with a focus on concepts relevant to the IB Computer Science curriculum.

双缝干涉实验是波动行为最具标志性的演示之一,揭示了相干光如何在屏幕上产生明暗相间的条纹。从计算机科学的角度看,模拟这种现象为应用计算思维、数值方法和可视化技术提供了绝佳的机会。通过对波的叠加进行建模、将连续域离散化并渲染所得的光强图案,学生可以加深对物理和算法的理解。本文探讨使用现代编程环境构建稳健的双缝干涉数字模型所涉及的步骤,重点关注与 IB 计算机科学课程相关的概念。


1. The Physics Behind Interference | 干涉背后的物理原理

tiple of half the wavelength, destructive interference cancels the waves, producing a dark fringe. The angular position θ of the m-th bright fringe is given by d sinθ = mλ, where d is the slit separation and λ is the wavelength.

当两列具有相同频率和振幅的相干光波到达屏幕上某一点时,它们会叠加。如果两列波的路程差是波长的整数倍,则发生相长干涉,观察到亮纹。如果路程差是半波长的奇数倍,则发生相消干涉,形成暗纹。第 m 级亮纹的角位置 θ 由 d sinθ = mλ 给出,其中 d 是缝间距,λ 是波长。

s proportional to cos²(π d y / (λL)). An accurate simulation must reproduce this oscillatory pattern without relying on the approximation if we require high precision at large angles.

出于计算目的,更方便的方法是处理放置在距离狭缝 L 处的平面屏幕上的强度分布。假设 L 远大于 d,小角近似给出屏幕上的竖向位移 y ≈ L tanθ。点 y 处的强度 I 与 cos²(π d y / (λL)) 成正比。若要在大角度下获得高精度,精确的模拟必须再现这种振荡模式,而不依赖近似。


2. Mathematical Model for Double Slit | 双缝的数学模型

φ = (2π d sinθ) / λ. Using the screen coordinates, this becomes I(y) = I₀ cos²(π d y / (λ √y² + L² mon simplification sets I₀ = 1 for normalised intensity, producing values between 0 and 1.

宽度可忽略的两条相同狭缝产生的强度基本方程为 I(θ) = I₀ cos²(φ/2),其中 φ = (2π d sinθ) / λ。采用屏幕坐标,该式变为 I(y) = I₀ cos²(π d y / (λ √y² + L²))。在数值上,我们计算每个点的相位差 φ,然后计算余弦平方函数。该模型必须处理 y 为零且不发生除零错的情况。常见的简化方法是将归一化强度设为 I₀ = 1,使数值介于 0 和 1 之间。

it width. For IB Computer Science projects, adding the diffraction envelope increases the realism of the simulation and introduces an additional parameter that students can vary interactively.

另一个重要效应是由每条狭缝有限宽度引起的衍射包络。为包含此效应,强度需由一个 sinc² 项调制:I(y) = I₀ cos²(φ/2) × sinc²(β/2),其中 β = (2π a sinθ) / λ,a 为缝宽。对于 IB 计算机科学项目,添加衍射包络可增加模拟的真实性,并引入学生可交互改变的额外参数。


3. Discretisation and Sampling | 离散化与采样

A continuous intensity function must be sampled at discrete points to produce a digital image. The screen is represented as a 2D array of pixels, and we compute the intensity at each pixel coordinate (x, y). The y-axis corresponds to the vertical displacement, while the x-axis is usually constant. Choosing an appropriate sampling frequency is critical to avoid aliasing: according to the Nyquist theorem, the sampling rate should be at least twice the maximum spatial frequency present in the pattern. The spatial frequency is determined by d/(λL), so the pixel spacing must be smaller than half the fringe width.

连续的强度函数必须在离散点处采样,以生成数字图像。屏幕表示为像素的二维数组,我们计算每个像素坐标 (x, y) 处的强度。y 轴对应垂直位移,x 轴通常不变。选择合适的采样频率对于避免混叠至关重要:根据奈奎斯特定理,采样率至少应为图案中最高空间频率的两倍。空间频率由 d/(λL) 决定,因此像素间距必须小于条纹宽度的一半。

In practice, a 1D simulation along a vertical line is often sufficient for basic visualisation. We define an array of y-values using the linspace function over a range that captures several orders of fringes. The number of sampling points N should be large enough, typically 2000 or more, to render smooth curves. For a full 2D rendering, we can use meshgrid to create coordinate matrices and compute intensity in a vectorised manner, which is essential for performance.

实际上,沿一条垂直线的一维模拟通常足以实现基本可视化。我们使用 linspace 函数定义一个 y 值数组,该范围涵盖若干级条纹。采样点数 N 应足够大,通常为 2000 或以上,以呈现平滑的曲线。对于完整的二维渲染,我们可以使用 meshgrid 创建坐标矩阵,并以向量化方式计算强度,这对性能至关重要。


4. Implementing the Simulation in Python | 用 Python 实现模拟

Python, with its rich scientific libraries, is an ideal language for simulating interference. A minimal implementation involves defining the physical parameters (d, λ, L, a) and computing the intensity for an array of y positions. The core logic can be expressed in a few lines using NumPy. For example:

Python 拥有丰富的科学库,是模拟干涉的理想语言。最小实现包括定义物理参数(d、λ、L、a)并计算 y 位置数组的强度。核心逻辑可使用 NumPy 用几行代码表达。例如:

term, we must handle the sinc function carefully to avoid division by zero at β = 0. Using np.sinc which is defined as sin(πx)/(πx) and is 1 at zero is recommended. The combined intensity becomes intensity = (np.cos(phi/2)**2) * (np.sinc(beta/(2*np.pi))**2). A complete simulation should be encapsulated in a function that takes parameters and returns intensity arrays.

在加入衍射项时,我们必须小心处理 sinc 函数,避免 β = 0 时出现除零错误。推荐使用 np.sinc,它定义为 sin(πx)/(πx) 且在零点取值为 1。合并强度变为 intensity = (np.cos(phi/2)**2) * (np.sinc(beta/(2*np.pi))**2)。完整的模拟应封装在一个函数中,该函数接受参数并返回强度数组。


5. Displaying the Interference Pattern | 显示干涉图样

Visualisation brings the numerical data to life. Using Matplotlib, a 1D intensity plot shows the characteristic oscillating curve, while a 2D image plot creates a realistic fringe pattern. For a 2D display, we construct a grid of (x, y) coordinates where the x-axis is a constant intensity along the horizontal slit axis, and the y-dependent intensity is replicated across columns. This can be achieved by broadcasting a 1D intensity array into a 2D array. A colour map such as 'gray' or 'inferno' enhances the contrast between bright and dark fringes.

可视化让数值数据栩栩如生。使用 Matplotlib,一维强度图可显示特征振荡曲线,而二维图像图可创建逼真的条纹图案。对于二维显示,我们构建一个 (x, y) 坐标网格,其中 x 轴是沿水平缝轴的恒定强度,而与 y 相关的强度在各列之间复制。这可以通过将一维强度数组广播为二维数组来实现。使用 'gray' 或 'inferno' 等颜色映射可增强明暗条纹之间的对比度。

The code to generate a 2D plot might look like:

生成二维图的代码可能如下:

To make the display interactive, sliders can be added using matplotlib.widgets or an external library like ipywidgets, allowing the user to change wavelength or slit separation in real time and observe the effect on the fringe spacing.

为了让显示可交互,可以使用 matplotlib.widgets 或 ipywidgets 等外部库添加滑块,使用户能够实时改变波长或缝间距,并观察条纹间距的变化。


6. Optimising Performance with NumPy | 使用 NumPy 优化性能

Brute-force loops in pure Python can be extremely slow, especially for high-resolution 2D grids. NumPy's vectorised operations execute compiled C code under the hood, drastically reducing computation time. When calculating trigonometric functions or power operations on large arrays, vectorisation is vital. For instance, computing intensity for 1 million points with a loop might take seconds, whereas the vectorised equivalent completes in milliseconds. This performance gap becomes critical when building real-time interactive simulations for IB Internal Assessments.

纯 Python 中的暴力循环可能极其缓慢,尤其是对于高分辨率的二维网格。NumPy 的向量化运算在底层执行编译后的 C 代码,从而大幅缩短计算时间。在对大型数组进行三角函数或幂运算时,向量化至关重要。例如,用循环计算 100 万个点的强度可能需要数秒,而等价的向量化操作可在数毫秒内完成。在为 IB 内部评估构建实时交互式模拟时,这种性能差距变得至关重要。

Profiling tools such as cProfile or the %timeit magic command in Jupyter can help identify bottlenecks. Common techniques include pre-allocating arrays, avoiding unnecessary temporary arrays, and using in-place operations where possible. For the double slit simulation, ensuring that all mathematical operations are performed on NumPy arrays rather than Python scalars is the primary optimisation strategy. Additionally, using single-precision floats (float32) can halve memory usage and speed up calculations on some hardware without sacrificing visible quality.

诸如 cProfile 或 Jupyter 中的 %timeit 魔法命令等性能分析工具有助于识别瓶颈。常用技术包括预分配数组、避免不必要的临时数组以及尽可能使用原地操作。对于双缝模拟,确保所有数学运算都在 NumPy 数组上执行而非 Python 标量,是主要的优化策略。此外,使用单精度浮点数(float32)可以在不牺牲可见质量的情况下将内存使用量减半并加快某些硬件上的计算速度。


广告 / Sponsored

7. Adding Interactivity | 增加交互性

Interactive controls transform a static plot into an exploratory learning tool. With the matplotlib.widgets.Slider class, we can link parameters like wavelength, slit separation, and screen distance to a callback function that recomputes and redraws the pattern. This teaches event-driven programming and graphical user interface (GUI) concepts, which are part of the IB Computer Science syllabus. The update function should be kept lightweight to maintain a responsive interface; thus, any heavy computation should rely on pre-allocated structures.

交互式控件将静态图转变为探索性学习工具。通过 matplotlib.widgets.Slider 类,我们可以将波长、缝间距和屏幕距离等参数与一个回调函数关联,该函数重新计算并重绘图案。这教授了事件驱动编程和图形用户界面(GUI)概念,它们都是 IB 计算机科学教学大纲的一部分。更新函数应保持轻量以维持响应迅速的界面;因此,任何繁重的计算都应依赖预分配的结构。

Alternatively, web-based visualisation using libraries like Plotly Dash or Bokeh allows deployment as a standalone web application. This approach requires understanding of server-client architecture and can be an excellent topic for the IB Computer Science project. By embedding the simulation in a web page, students can demonstrate skills in HTML, CSS and JavaScript alongside Python, showcasing a full-stack development capability.

或者,使用 Plotly Dash 或 Bokeh 等库进行基于网络的可视化,可以将其作为独立的 Web 应用程序部署。这种方法需要理解服务器 - 客户端架构,并可作为 IB 计算机科学项目的绝佳主题。通过将模拟嵌入网页,学生可以展示 HTML、CSS 和 JavaScript 与 Python 的技能,展现全栈开发能力。


8. Extending to Multiple Slits | 扩展到多缝

inθ)/λ. A direct implementation of this formula must guard against the denominator approaching zero at diffraction orders. Numerically, we can use a small epsilon to avoid singularities, or compute the limit analytically by returning N² when sin(β/2) is close to zero.

一旦双缝模拟成功运行,将其扩展到 N 条狭缝可以强化叠加概念。N 条相同等距狭缝的光强由 I(θ) = I₀ (sin(Nβ/2) / sin(β/2))² 给出,其中 β = (2π d sinθ)/λ。直接实现此公式时必须防止在衍射级次处分母趋近于零。在数值上,我们可以使用一个小 epsilon 来避免奇点,或者在 sin(β/2) 接近零时通过解析方式返回 N² 来计算极限。

This extension provides a natural progression into the study of diffraction gratings, which are fundamental in spectroscopy. From a computing viewpoint, the multi-slit case offers a chance to discuss code reuse and modular design. The core intensity function can be written generally, with the number of slits as a parameter. This reduces duplication and exemplifies good software engineering practice. Students can then create a single program that supports double, triple, and N-slit configurations with a simple parameter change.

这一扩展为研究衍射光栅提供了自然的进阶途径,而衍射光栅是光谱学的基础。从计算的角度看,多缝情况为讨论代码复用和模块化设计提供了机会。核心强度函数可以写成通用的,将狭缝数目作为参数。这减少了重复,体现了良好的软件工程实践。学生随后可以创建一个单一程序,只需简单更改参数即可支持双缝、三缝和 N 缝配置。


9. Numerical Considerations and Edge Cases | 数值注意事项与边界情况

Robust simulations must handle edge cases such as extremely small slit separations or very large screen distances. When d is comparable to λ, the fringes become very wide, and the sampling grid must be adjusted accordingly. Conversely, when L is very small, the small-angle approximation breaks down and the full trigonometric relation must be used. Another subtlety arises when simulating monochromatic light: if we wish to simulate white light, we must sum the intensity patterns for multiple wavelengths and combine them into an RGB image, which introduces colour mapping algorithms.

稳健的模拟必须处理边界情况,例如极小的狭缝间距或非常大的屏幕距离。当 d 与 λ 可比时,条纹变得非常宽,必须相应地调整采样网格。相反,当 L 非常小时,小角近似失效,必须使用完整的三角函数关系。在模拟单色光时还会出现另一个细微之处:若想模拟白光,我们必须对多个波长的强度图案求和,并将它们组合成 RGB 图像,这引入了颜色映射算法。

Floating-point precision can cause artifacts in the computed intensity, particularly near minima where intensity should be zero but small negative values might appear due to rounding errors. Clipping values to the range [0, 1] eliminates such artifacts. Also, when using the sinc function, it is prudent to replace values evaluated at exactly zero with 1 using np.where to avoid NaN errors. Documenting these design decisions is valuable for the technical write-up of an IB project.

浮点精度可能在计算出的强度中引起伪影,尤其是当光强应为零而因舍入误差出现小的负值时。将数值裁剪到 [0, 1] 范围可消除此类伪影。此外,在使用 sinc 函数时,最好使用 np.where 将恰好在零点处计算的值替换为 1,以避免 NaN 错误。记录这些设计决策对于 IB 项目的技术报告非常有价值。


10. Computational Complexity and Parallel Processing | 计算复杂度与并行处理

For a static image with fixed parameters, the time complexity of the intensity calculation is O(N), where N is the number of pixels. However, for animated or interactive high-resolution simulations, the repeated computation demands optimisation. One approach is parallel processing: since each pixel's intensity is independent, the calculation is embarrassingly parallel. Using Python's multiprocessing module or Numba just-in-time compilation can distribute the workload across multiple CPU cores, achieving near-linear speedup.

对于参数固定的静态图像,强度计算的时间复杂度为 O(N),其中 N 为像素数量。然而,对于动画或交互式高分辨率模拟,反复计算需要优化。一种方法是并行处理:由于每个像素的强度彼此独立,该计算是“易并行”的。使用 Python 的 multiprocessing 模块或 Numba 即时编译可以将工作负载分布到多个 CPU 核心上,实现近乎线性的加速。

GPU acceleration through libraries like CuPy enables real-time simulation at very high resolutions. While this may be an advanced topic, it connects well with the IB Computer Science option on resource management and introduces students to heterogeneous computing. Even without a GPU, understanding the theoretical speedup from vectorisation and parallel execution deepens algorithmic thinking.

通过 CuPy 等库进行的 GPU 加速可以在极高分辨率下实现实时模拟。虽然这可能是一个高级主题,但它与 IB 计算机科学中关于资源管理的选项部分相关联,并向学生介绍了异构计算。即使没有 GPU,理解向量化和并行执行带来的理论加速也能加深算法思维。


11. Validation Against Physical Theory | 与物理理论的验证

A crucial step in any simulation is validation. The predicted fringe positions from the computational model should be compared with the analytical formula ym ite unit tests that assert the simulated intensity is maximal at these positions and minimal midway between them. Additionally, comparing the output with known experimental data or reference images builds confidence in the model' ience project, a thorough evaluation section should discuss the accuracy and limitations of the simulation.

任何模拟的关键步骤都是验证。计算模型预测的条纹位置应与解析公式 ym = m λ L / d(对于小角度)进行比较。可以编写单元测试,断言模拟强度在这些位置处最大,而在它们中间最小。此外,将输出与已知实验数据或参考图像进行比较,可以建立对模型正确性的信心。对于 IB 计算机科学项目,详尽的评估部分应讨论模拟的准确性和局限性。

Automating validation using Python's unittest framework is a professional practice. A test could check that the intensity profile has exactly the expected number of peaks within a given y-range, or that the peak-to-peak spacing matches the theoretical value within a tolerance. These computational tests directly support the strand of 'testing and evaluation' in the IB Computer Science internal assessment criteria.

使用 Python 的 unittest 框架进行自动验证是一种专业实践。测试可以检查强度分布在给定 y 范围内是否具有正好预期数量的峰值,或者峰 - 峰间距与理论值在误差范围内匹配。这些计算测试直接支持了 IB 计算机科学内部评估标准中的“测试与评估”环节。


12. Project Ideas for IB Computer Science | IB 计算机科学项目构思

Building a double slit simulation can serve as the foundation for a compelling IB Computer Science internal assessment (IA). A successful project would involve a clear client scenario, such as a physics teacher wanting an interactive teaching aid. The system could provide adjustable parameters, display graphical output, and possibly export numerical data for further analysis. The development would follow the standard software development life cycle (SDLC), with documented analysis, design, implementation and evaluation phases.

构建双缝模拟可作为引人注目的 IB 计算机科学内部评估(IA)的基础。一个成功的项目将涉及明确的客户场景,例如一位希望拥有交互式教学辅助工具的物理教师。该系统可提供可调参数、显示图形输出,并可能导出数值数据以供进一步分析。开发将遵循标准的软件开发生命周期(SDLC),包含文档化的分析、设计、实施和评估阶段。

Criterion (标准)How the Simulation Addresses It (模拟如何满足)
Planning (规划)Gantt chart for coding GUI, physics model, and testing (用于 GUI、物理模型编码及测试的甘特图)
Design (设计)Flowcharts of algorithm, UML class diagram for object-oriented version (算法流程图,面向对象版本的 UML 类图)
Development (开发)Modular Python code with functions for physics, I/O, and GUI (含物理、I/O 和 GUI 函数的模块化 Python 代码)
Evaluation (评估)Feedback from physics teacher, accuracy benchmarks, performance metrics (物理教师反馈、准确性基准、性能指标)

Advanced extensions could include simulating the interference of non-optical waves, such as sound or water waves, or incorporating realistic noise to mimic experimental conditions. Such features demonstrate a deeper level of computational thinking and can elevate the IA grade. The project also provides an opportunity to integrate with the Theory of Knowledge (TOK) by discussing models and reality.

高级扩展可以包括模拟非光波的干涉,例如声波或水波,或加入逼真的噪声以模仿实验条件。这些特性展示了更深层次的计算思维,并能提高 IA 成绩。该项目还通过讨论模型与现实,提供了与知识论(TOK)相结合的机会。


Published by TutorHao | Computer Science Revision Series | aleveler.com

广告 / Sponsored
IBDP国际文凭计算机科学学生用书 高级及标准水平 Computer Science for the IB Diplo…
计算机 备考教辅 · 正版现货 · 与本文内容相关
查看详情 / View on Taobao参考价 ¥524.0

更多咨询请联系16621398022(同微信)

备考资讯每日更新,关注不错过
考纲变化 · 科目分析 · 学习方法
扫码关注公众号 tutorhao
在微信里长按二维码识别关注
或截图后用「扫一扫 → 相册」选择本图
公众号:tutorhao