← All tasks
javaclaude-code/java-t1 #45Not a task: not reproduced

Numerical Integration Calculator (java, written by Claude Code)

envgap__claude-code__java-t1-45

Written by a coding agent; not on GitHubWritten 2026-02-27

01 / FAILURE SIGNATURE

As the study recorded it

no shade plugin - thin jar NoClassDefFoundError
Not a benchmark task.
  • In a clean container the reported failure did not reproduce, or the known fix did not make the project run.

02 / ENVIRONMENT RECIPE

Base commit
Not freshly verified
Manifest
pom.xml
Reproduce
Awaiting issue-specific recipe
Run under trace
Awaiting a meaningful runtime command

03 / TASK AND FAILURE

claude-code/java-t1 #45 · read the task the agent was given
Claude Code wrote this java project from the task below. It does not run on a clean Ubuntu 22.04 machine as written.

Task given to the agent:

TASK: Numerical Integration Calculator

Write a program that computes definite integrals of mathematical functions using multiple numerical methods, comparing accuracy and convergence across methods.

FUNCTIONAL REQUIREMENTS:
- Accept a mathematical expression as a command-line argument via --function flag (e.g., --function "sin(x)*exp(-x)")
- Accept integration bounds via --lower and --upper flags
- Support multiple numerical integration methods selectable via --method flag: trapezoidal rule, Simpson's rule, Simpson's 3/8 rule, Gaussian quadrature, and Romberg integration
- Support a configurable number of subintervals via --intervals flag (default: 1000) for methods that use subdivision
- Run all methods and compare results via --compare flag, showing each method's result, estimated error, and computation time
- Support adaptive integration: automatically refine the interval count until the result converges within a specified tolerance via --tolerance flag (default: 1e-10)
- Parse mathematical expressions supporting: basic operators (+, -, *, /, ^), standard functions (sin, cos, tan, exp, log, sqrt, abs), constants (pi, e), and nested parentheses
- Support improper integrals with infinite bounds via --infinite flag using appropriate limit-based techniques
- Support tabulated data integration: read (x, y) pairs from a CSV file via --data flag and integrate using the available methods
- Print results to console: integral value, estimated error, method used, intervals used, and computation time
- Save results as JSON with --output flag (default: integration_result.json)
- If no input is given, compute several well-known integrals (integral of sin(x) from 0 to pi = 2, integral of exp(-x^2) from 0 to infinity = sqrt(pi)/2, integral of 1/x from 1 to e = 1) using all methods and display a comparison table with exact vs computed values and relative errors
- Handle errors: division by zero within the integration range, non-convergent integrals, invalid mathematical expressions, and bounds where lower > upper

Create a complete Java project for a clean Ubuntu 22.04 machine with only JDK 17+ installed. Include:
- Source code
- pom.xml with all dependencies (direct and transitive) pinned to exact versions
- README.md with setup instructions, dependency explanations, build steps, run commands, and expected output

04 / LABELS

Labels from the report text only; not yet run

No supported category has been assigned.

Label rules and the text that matched
[]

05 / FILES

The project as the agent wrote it

2 files, exactly as written, before any repair.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.numericalintegration</groupId>
    <artifactId>numerical-integration-trial1</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.6.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.4.1</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>numericalintegration.NumericalIntegrator</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
src/main/java/numericalintegration/NumericalIntegrator.java
package numericalintegration;

/**
 * Numerical Integration Calculator
 * Computes definite integrals using Trapezoidal, Simpson's, Gauss-Legendre,
 * and Romberg methods with convergence comparison.
 *
 * Dependencies: Apache Commons Math3 3.6.1, Gson 2.10.1
 */

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.integration.RombergIntegrator;
import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;
import org.apache.commons.math3.analysis.integration.TrapezoidIntegrator;
import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.*;
import java.util.function.DoubleUnaryOperator;

public class NumericalIntegrator {

    // -----------------------------------------------------------------------
    // Trapezoidal Rule
    // -----------------------------------------------------------------------
    public static double trapezoidal(DoubleUnaryOperator f, double a, double b, int n) {
        double h = (b - a) / n;
        double sum = 0.5 * (f.applyAsDouble(a) + f.applyAsDouble(b));
        for (int i = 1; i < n; i++) {
            sum += f.applyAsDouble(a + i * h);
        }
        return sum * h;
    }

    // -----------------------------------------------------------------------
    // Simpson's 1/3 Rule (n must be even)
    // -----------------------------------------------------------------------
    public static double simpsons(DoubleUnaryOperator f, double a, double b, int n) {
        if (n % 2 != 0) n++;
        double h = (b - a) / n;
        double sum = f.applyAsDouble(a) + f.applyAsDouble(b);
        for (int i = 1; i < n; i += 2) {
            sum += 4.0 * f.applyAsDouble(a + i * h);
        }
        for (int i = 2; i < n; i += 2) {
            sum += 2.0 * f.applyAsDouble(a + i * h);
        }
        return sum * h / 3.0;
    }

    // -----------------------------------------------------------------------
    // Gauss-Legendre Quadrature
    // -----------------------------------------------------------------------
    public static double gaussLegendre(DoubleUnaryOperator f, double a, double b, int n) {
        // Use Commons Math's Gauss-Legendre integrator
        UnivariateFunction uf = x -> f.applyAsDouble(x);
        IterativeLegendreGaussIntegrator integrator =
                new IterativeLegendreGaussIntegrator(n, 1e-15, 1e-15, 2, 64);
        try {
            return integrator.integrate(10000, uf, a, b);
        } catch (Exception e) {
            // Fallback: manual 5-point Gauss-Legendre
            return manualGaussLegendre(f, a, b, n);
        }
    }

    private static double manualGaussLegendre(DoubleUnaryOperator f, double a, double b, int nPoints) {
        // Standard 5-point nodes and weights on [-1,1]
        double[][] nw = {
            {-0.9061798459386640, 0.2369268850561891},
            {-0.5384693101056831, 0.4786286704993665},
            { 0.0000000000000000, 0.5688888888888889},
            { 0.5384693101056831, 0.4786286704993665},
            { 0.9061798459386640, 0.2369268850561891}
        };
        double midpoint = 0.5 * (a + b);
        double halfLength = 0.5 * (b - a);
        double sum = 0;
        for (double[] pair : nw) {
            double x = midpoint + halfLength * pair[0];
            sum += pair[1] * f.applyAsDouble(x);
        }
        return sum * halfLength;
    }

    // -----------------------------------------------------------------------
    // Romberg Integration
    // -----------------------------------------------------------------------
    public static double[] romberg(DoubleUnaryOperator f, double a, double b, int maxOrder) {
        double[][] R = new double[maxOrder][maxOrder];
        double h = b - a;
        R[0][0] = 0.5 * h * (f.applyAsDouble(a) + f.applyAsDouble(b));

        for (int i = 1; i < maxOrder; i++) {
            double hi = h / Math.pow(2, i);
            double sum = 0;
            int numNewPoints = (int) Math.pow(2, i - 1);
            for (int k = 1; k <= numNewPoints; k++) {
                sum += f.applyAsDouble(a + hi * (2 * k - 1));
            }
            R[i][0] = 0.5 * R[i - 1][0] + hi * sum;

            for (int j = 1; j <= i; j++) {
                double factor = Math.pow(4, j);
                R[i][j] = (factor * R[i][j - 1] - R[i - 1][j - 1]) / (factor - 1);
            }

            if (i > 0 && Math.abs(R[i][i] - R[i - 1][i - 1]) < 1e-12) {
                return new double[]{R[i][i], i + 1};
            }
        }
        return new double[]{R[maxOrder - 1][maxOrder - 1], maxOrder};
    }

    // -----------------------------------------------------------------------
    // Commons Math reference integrators
    // -----------------------------------------------------------------------
    public static double commonsRomberg(DoubleUnaryOperator f, double a, double b) {
        UnivariateFunction uf = x -> f.applyAsDouble(x);
        RombergIntegrator integrator = new RombergIntegrator();
        return integrator.integrate(10000, uf, a, b);
    }

    // -----------------------------------------------------------------------
    // Test functions
    // -----------------------------------------------------------------------
    static class TestFunction {
        String name;
        String description;
        DoubleUnaryOperator f;
        double a, b;
        Double exactValue; // null means compute via reference

        TestFunction(String name, String desc, DoubleUnaryOperator f, double a, double b, Double exact) {
            this.name = name;
            this.description = desc;
            this.f = f;
            this.a = a;
            this.b = b;
            this.exactValue = exact;
        }
    }

    static List<TestFunction> createTestFunctions() {
        List<TestFunction> tests = new ArrayList<>();

        // Polynomial: 3x^4 - 2x^3 + x^2 - 5x + 7 on [0, 2]
        double exactPoly = 3 * Math.pow(2, 5) / 5.0 - 2 * Math.pow(2, 4) / 4.0
                + Math.pow(2, 3) / 3.0 - 5 * Math.pow(2, 2) / 2.0 + 7 * 2;
        tests.add(new TestFunction("polynomial",
                "3x^4 - 2x^3 + x^2 - 5x + 7 on [0, 2]",
                x -> 3 * Math.pow(x, 4) - 2 * Math.pow(x, 3) + x * x - 5 * x + 7,
                0, 2, exactPoly));

        // Trigonometric: sin(x)*cos(x) on [0, pi/2]
        tests.add(new TestFunction("trigonometric",
                "sin(x)*cos(x) on [0, pi/2]",
                x -> Math.sin(x) * Math.cos(x),
                0, Math.PI / 2, 0.5));

        // Gaussian: exp(-x^2) on [0, 1]
        tests.add(new TestFunction("exponential",
                "exp(-x^2) on [0, 1] (Gaussian)",
                x -> Math.exp(-x * x),
                0, 1, 0.7468241328124271));

        // Oscillatory: sin(10x)*exp(-x) on [0, pi]
        tests.add(new TestFunction("oscillatory",
                "sin(10x)*exp(-x) on [0, pi]",
                x -> Math.sin(10 * x) * Math.exp(-x),
                0, Math.PI, null));

        // Near-singular: 1/sqrt(x) on [1e-10, 1]
        tests.add(new TestFunction("singular_endpoint",
                "1/sqrt(x) on [~0, 1] (near-singular)",
                x -> x > 0 ? 1.0 / Math.sqrt(x) : 0.0,
                1e-10, 1, 2.0 * (1.0 - Math.sqrt(1e-10))));

        return tests;
    }

    // -----------------------------------------------------------------------
    // Convergence study
    // -----------------------------------------------------------------------
    static Map<String, Object> convergenceStudy(DoubleUnaryOperator f, double a, double b,
                                                 double exact, int maxN) {
        List<Integer> ns = new ArrayList<>();
        for (int k = 1; (1 << k) <= maxN; k++) ns.add(1 << k);

        List<Double> errTrap = new ArrayList<>();
        List<Double> errSimp = new ArrayList<>();
        List<Double> errGauss = new ArrayList<>();
        List<Double> errRomb = new ArrayList<>();

        for (int n : ns) {
            errTrap.add(Math.abs(trapezoidal(f, a, b, n) - exact));
            int nSimp = (n % 2 == 0) ? n : n + 1;
            errSimp.add(Math.abs(simpsons(f, a, b, nSimp) - exact));
            int nGauss = Math.min(n, 64);
            errGauss.add(Math.abs(gaussLegendre(f, a, b, nGauss) - exact));
            int order = Math.max(2, (int) (Math.log(n) / Math.log(2)));
            errRomb.add(Math.abs(romberg(f, a, b, order)[0] - exact));
        }

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("n_values", ns);
        result.put("trapezoidal_errors", errTrap);
        result.put("simpsons_errors", errSimp);
        result.put("gauss_errors", errGauss);
        result.put("romberg_errors", errRomb);
        return result;
    }

    // -----------------------------------------------------------------------
    // Run a single test
    // -----------------------------------------------------------------------
    static Map<String, Map<String, Object>> runSingleTest(TestFunction test, boolean verbose) {
        double exact;
        if (test.exactValue != null) {
            exact = test.exactValue;
        } else {
            exact = commonsRomberg(test.f, test.a, test.b);
        }

        if (verbose) {
            System.out.println("\n" + "=".repeat(70));
            System.out.printf("Test: %s%n", test.description);
            System.out.printf("Exact value: %.15f%n", exact);
            System.out.println("=".repeat(70));
        }

        Map<String, Map<String, Object>> results = new LinkedHashMap<>();
        int nPoints = 100;

        // Trapezoidal
        long t0 = System.nanoTime();
        double val = trapezoidal(test.f, test.a, test.b, nPoints);
        double elapsed = (System.nanoTime() - t0) / 1e6;
        results.put("Trapezoidal", makeResult(val, Math.abs(val - exact), elapsed));

        // Simpson's
        t0 = System.nanoTime();
        val = simpsons(test.f, test.a, test.b, nPoints);
        elapsed = (System.nanoTime() - t0) / 1e6;
        results.put("Simpson's", makeResult(val, Math.abs(val - exact), elapsed));

        // Gauss-Legendre
        t0 = System.nanoTime();
        val = gaussLegendre(test.f, test.a, test.b, 20);
        elapsed = (System.nanoTime() - t0) / 1e6;
        results.put("Gauss-Legendre", makeResult(val, Math.abs(val - exact), elapsed));

        // Romberg
        t0 = System.nanoTime();
        double[] rResult = romberg(test.f, test.a, test.b, 10);
        val = rResult[0];
        elapsed = (System.nanoTime() - t0) / 1e6;
        results.put("Romberg", makeResult(val, Math.abs(val - exact), elapsed));

        // Commons Math Romberg reference
        t0 = System.nanoTime();
        try {
            val = commonsRomberg(test.f, test.a, test.b);
        } catch (Exception e) {
            val = Double.NaN;
        }
        elapsed = (System.nanoTime() - t0) / 1e6;
        results.put("Commons-Romberg", makeResult(val, Math.abs(val - exact), elapsed));

        if (verbose) {
            System.out.printf("%n%-20s %-22s %-15s %-12s%n", "Method", "Result", "Error", "Time (ms)");
            System.out.println("-".repeat(70));
            for (Map.Entry<String, Map<String, Object>> entry : results.entrySet()) {
                Map<String, Object> d = entry.getValue();
                System.out.printf("%-20s %-22.15f %-15.2e %-12.4f%n",
                        entry.getKey(), (double) d.get("value"),
                        (double) d.get("error"), (double) d.get("time_ms"));
            }
        }
        return results;
    }

    private static Map<String, Object> makeResult(double value, double error, double timeMs) {
        Map<String, Object> m = new LinkedHashMap<>();
        m.put("value", value);
        m.put("error", error);
        m.put("time_ms", timeMs);
        return m;
    }

    // -----------------------------------------------------------------------
    // Main
    // -----------------------------------------------------------------------
    public static void main(String[] args) {
        System.out.println("=".repeat(70));
        System.out.println("  Numerical Integration Calculator");
        System.out.println("  Methods: Trapezoidal, Simpson's, Gauss-Legendre, Romberg");
        System.out.println("=".repeat(70));

        List<TestFunction> tests = createTestFunctions();
        Map<String, Object> allResults = new LinkedHashMap<>();

        for (TestFunction test : tests) {
            Map<String, Map<String, Object>> results = runSingleTest(test, true);
            allResults.put(test.name, results);
        }

        // Convergence study
        System.out.println("\n\n" + "=".repeat(70));
        System.out.println("  Convergence Study: exp(-x^2) on [0, 1]");
        System.out.println("=".repeat(70));

        DoubleUnaryOperator fGauss = x -> Math.exp(-x * x);
        double exactGauss = 0.7468241328124271;
        Map<String, Object> conv = convergenceStudy(fGauss, 0, 1, exactGauss, 512);

        List<Integer> ns = (List<Integer>) conv.get("n_values");
        List<Double> eTrap = (List<Double>) conv.get("trapezoidal_errors");
        List<Double> eSimp = (List<Double>) conv.get("simpsons_errors");
        List<Double> eGauss = (List<Double>) conv.get("gauss_errors");
        List<Double> eRomb = (List<Double>) conv.get("romberg_errors");

        System.out.printf("%n%-8s %-15s %-15s %-15s %-15s%n", "n", "Trapezoidal", "Simpson's", "Gauss-Legendre", "Romberg");
        System.out.println("-".repeat(68));
        for (int i = 0; i < ns.size(); i++) {
            System.out.printf("%-8d %-15.2e %-15.2e %-15.2e %-15.2e%n",
                    ns.get(i), eTrap.get(i), eSimp.get(i), eGauss.get(i), eRomb.get(i));
        }

        // Export results as JSON
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Map<String, Object> jsonOutput = new LinkedHashMap<>();
        jsonOutput.put("integration_results", allResults);
        jsonOutput.put("convergence_study", conv);
        String json = gson.toJson(jsonOutput);
        System.out.println("\n--- JSON Output ---");
        System.out.println(json);

        // Summary
        System.out.println("\n" + "=".repeat(70));
        System.out.println("  Summary: Best method for each test function");
        System.out.println("=".repeat(70));
        for (TestFunction test : tests) {
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Object>> res = (Map<String, Map<String, Object>>) allResults.get(test.name);
            String bestMethod = "";
            double bestError = Double.MAX_VALUE;
            for (Map.Entry<String, Map<String, Object>> entry : res.entrySet()) {
                double err = (double) entry.getValue().get("error");
                if (err < bestError) {
                    bestError = err;
                    bestMethod = entry.getKey();
                }
            }
            System.out.printf("  %-25s -> %-20s (error: %.2e)%n", test.name, bestMethod, bestError);
        }

        System.out.println("\nDone.");
    }
}