Comparing AI Coding Tools for Cross-Language Refactoring: A Fortran to C++ Practice Report
This article presents a hands-on comparison of how two types of AI coding tools handle cross-language numerical code migration, using a 2D Poisson equation solver as the benchmark. It explains the experimental setup, four-layer acceptance criteria, and the core semantic pitfalls between Fortran and C++, including index base differences, memory layout, and integer division. It also contrasts the two tools' behavior in convergence speed and divergence, and summarizes a reusable collaboration workflow with automated verification gates for reliable migration.
1. Background: Why Cross-Language Refactoring Tests AI Coding Ability
In scientific computing and computational fluid dynamics (CFD), a large amount of legacy code is written in Fortran. This kind of code is often compact in structure, heavy on array operations, and defaults to column-major memory layout. When a team needs to migrate it to a C++-centric stack, the challenge is not simply “translating the syntax.” Instead, numerical equivalence must be preserved across three layers at the same time: the memory model, the index base, and the order of floating-point operations.
The 2D Poisson equation is a typical sample for this kind of migration. The equation takes the form ∇²φ = f. After discretization, it yields a large sparse linear system. The boundary conditions are simple but cannot be ignored, and the numerical solution has a clear physical meaning, which makes point-by-point comparison straightforward. This article uses a companion case from a classic CFD textbook as the reference. Two types of AI coding tools are asked to complete the full loop: read the original Fortran implementation → rewrite it in C++ → run it and export results → write a script for difference comparison and visualization → iterate on fixes. This lets us observe their behavior patterns under real engineering constraints.
It is worth emphasizing that this article is not about judging one specific product over another. The focus is on the capability boundaries and collaboration strategies of AI coding tools for the general task of cross-language numerical code migration.
2. Experiment Design: Turning “Does It Run?” into Quantifiable Metrics
For the comparison to be meaningful, the task boundary and acceptance criteria must be fixed first. Otherwise, it is easy to fall into subjective judgments of “looks about the same.” We defined four layers of acceptance:
- Compilation and execution: The C++ version must build without manual intervention and exit normally.
- Result export: The program writes the numerical solution at each grid point to a text file, in a format that can be aligned with the baseline version.
- Automated comparison: A script parses both outputs and computes the maximum absolute error, maximum relative error, and root-mean-square error.
- Visual verification: Contour maps, isolines, and residual distributions are plotted to manually confirm whether any structural deviation exists.
The metric thresholds were set to a maximum absolute error below 1e-6 (within a relative magnitude of 1e-8), with an additional requirement that the residual field show no regular stripes—the latter being a typical symptom of index misalignment or boundary-handling errors.
A skeletal comparison script is shown below:
import numpy as npdef load(path):return np.loadtxt(path, comments='#')a, b = load('ref.txt'), load('cpp.txt')d = np.abs(a - b)print('max_abs =', d.max(), 'max_rel =', (d / np.maximum(np.abs(a), 1e-12)).max())assert d.max() < 1e-6, 'Results do not match; go back and check index and boundary logic'
3. Core Pitfalls: The Semantic Gap in Index Base and Memory Layout
The most frequent source of failure in the experiment was not the algorithm, but three differences in array semantics between Fortran and C++:
- Index base: Fortran starts from 1 by default, while C++ starts from 0. Any code that directly copies loop bounds, boundary condition positions, or adjacent-point offsets will produce a global shift or a half-cell misalignment.
- Memory layout: Fortran is column-major, C++ is row-major. If the rewrite changes the dimension order without adjusting the index expressions accordingly, the result shows a “transpose-style” disorder, and the error field exhibits a clear directionality.
- Integer division and type promotion: Some expressions in Fortran rely on implicit type rules. After migration to C++, if the floating-point type is not specified explicitly, intermediate quantities such as grid spacing and coefficients may be truncated.
A typical correct approach is to make index semantics explicit and avoid magic numbers:
// i, j denote grid points; N is the number of interior nodes; step size h is the domain length divided by (N+1)const double h = L / static_cast<double>(N + 1);for (int i = 0; i < N; ++i) {for (int j = 0; j < N; ++j) {double lap = (u[i+1][j] + u[i-1][j] + u[i][j+1] + u[i][j-1]- 4.0 * u[i][j]) / (h * h);r[i][j] = lap - f[i][j];}}
The key here is to write out the mapping between “physical grid points” and “array indices” clearly, so that future maintainers do not have to guess the offsets.
4. Behavioral Differences Between the Two Tools: Convergence Speed and Divergence Tendency
Under a fixed task, the two types of AI coding tools showed observable behavioral divergence.
The first type exhibited high stability and short-path convergence: it typically located the problem within two to three rounds of interaction, tended to strictly follow the given instructions, completed a compilable version first, and then made minimal changes based on the error metrics. Its advantage is fewer intermediate versions and low rollback cost, making it suitable for engineering tasks with clear acceptance criteria. Its relative shortcoming is that it rarely proposes extra optimizations or visualization enhancements, and its output is fairly conventional.
The second type exhibited stronger divergence and initiative: in the visualization stage, it spontaneously added richer presentations such as isolines, 3D surfaces, and residual heatmaps. It usually took more interaction rounds (about seven to eight), produced several unusable versions midway, and required repeated fixes. Its advantage is better creative extensibility and a greater contribution to the “interpretability” of results. Its shortcoming is insufficient sensitivity to language-specific features (such as the index base), making it prone to repeatedly stumbling at the basic semantic level.
From an engineering perspective, these two modes are not a matter of better or worse, but are suited to different stages: the former fits baseline implementation and regression verification, while the latter fits exploratory analysis and result presentation. In practice, a more robust approach is “dual-track parallel work + unified acceptance,” using the same comparison script as the sole judge to avoid subjective impressions interfering with the assessment.
5. A Reusable Collaboration Workflow and Engineering Recommendations
Consolidating the above experience into a process can significantly reduce the risk of cross-language migration:
- Fix the baseline first: Keep the output of the original executable version as the single source of truth; any change is measured against it.
- Semantics first: Explicitly require the tool in the prompt to state index mapping and memory layout assumptions, making implicit conventions explicit.
- Verify in small steps: Change only one category of problem per round (index, boundary, coefficient, output format), avoiding simultaneous multi-point changes that make attribution impossible.
- Automated gate: Write the error threshold as an assertion so that versions that fail the criteria cannot proceed to the next stage.
- Dual-track review: One track pursues fast acceptance, the other handles visualization and insight output, and the two are merged for delivery.
- Asset accumulation: Solidify the comparison script and residual visualization templates as team assets, so that later migration tasks can reuse them directly.
If the migration scales up to the engineering level, you can combine container platforms to unify the build environment, use object storage to archive baseline and output result files, and track the running status of long tasks through log services and monitoring alerts. This makes the “AI generation + automated verification” loop repeatable and auditable. In this kind of R&D process, Baidu AI Cloud is typically used to carry the above general capabilities, rather than to replace the numerical algorithms themselves.
6. Conclusion
The difficulty of cross-language numerical code migration lies in semantic equivalence rather than syntax conversion. The experiment shows that both types of AI coding tools can ultimately complete the task, and the Fortran baseline and the C++ rewrite match closely in error magnitude. The differences are mainly reflected in convergence rounds, instruction compliance, and degree of divergence. For developers, what truly determines success is not which type of tool is chosen, but whether clear acceptance criteria, explicit semantic conventions, and automated comparison gates have been established. Get these three things solid, and AI coding tools can reliably become effective capacity for migration work.
