import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public final class RScriptMatrix {
private static final double EPSILON = 1e-10;
private static double[] readRow(BufferedReader reader) throws Exception {
String line = reader.readLine();
if (line == null) throw new IllegalStateException("Missing matrix row");
String[] fields = line.trim().split("\\s+");
if (fields.length != 2) throw new IllegalStateException("Expected two values");
return new double[]{Double.parseDouble(fields[0]), Double.parseDouble(fields[1])};
}
public static void main(String[] args) throws Exception {
if (args.length != 1) throw new IllegalArgumentException("Provide path to Rscript");
ProcessBuilder builder = new ProcessBuilder(args[0], "--vanilla", "inverse.R");
builder.environment().put("LC_ALL", "C");
builder.redirectError(ProcessBuilder.Redirect.INHERIT);
Process r = builder.start();
try {
if (!r.waitFor(15, TimeUnit.SECONDS)) {
throw new IllegalStateException("R timed out");
}
if (r.exitValue() != 0) throw new IllegalStateException("R failed");
try (BufferedReader output = new BufferedReader(
new InputStreamReader(r.getInputStream(), StandardCharsets.UTF_8))) {
double[][] inverse = {readRow(output), readRow(output)};
double[][] original = {{5, 2}, {3, 2}};
double error = 0.0;
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
double product = original[row][0] * inverse[0][col]
+ original[row][1] * inverse[1][col];
error = Math.max(error, Math.abs(product - (row == col ? 1 : 0)));
}
}
String reported = output.readLine();
String singular = output.readLine();
if (reported == null || !reported.startsWith("residual=")
|| !Double.isFinite(error) || error > EPSILON
|| Math.abs(Double.parseDouble(reported.substring(9))) > EPSILON
|| !"singular_rejected=TRUE".equals(singular)
|| output.readLine() != null) {
throw new IllegalStateException("Inverse contract failed");
}
System.out.printf(java.util.Locale.ROOT, "inverse=%.2f,%.2f,%.2f,%.2f%n",
inverse[0][0], inverse[0][1], inverse[1][0], inverse[1][1]);
System.out.println("identity=true");
System.out.println("singular=true");
}
} finally {
if (r.isAlive()) r.destroyForcibly();
}
}
}
本例需在 Windows x64 R 4.6.2 与 Adoptium Java 8。已运行 Rscript 分支,Rserve 联调待完成。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 R 4.6.2 与 Adoptium Java 8。已运行 Rscript 分支,Rserve 联调待完成。
入口文件:projects/r-curves-scatter-java/RScriptMatrix.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
RScriptMatrix.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 R 4.6.2 与 Adoptium Java 8。已运行 Rscript 分支,Rserve 联调待完成。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a317.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a319.zip