Java代码计算C值时出现NaN输出问题排查请求
Hey there! Let's break down why you're getting NaN when calculating C[i][j] and how to fix it.
The Root Cause of NaN
Your issue is directly tied to this line:
C[i][j] = C[i][j] * (Math.sqrt(((Math.pow(U[i][j],2)/Math.pow(I[i][j],2)))-Math.pow(R[i],2)));
Math.sqrt() returns NaN when you pass a negative number to it. That means the expression inside the square root:
(Math.pow(U[i][j],2)/Math.pow(I[i][j],2)) - Math.pow(R[i],2)
is evaluating to a negative value for some of your input combinations.
This happens when (U[i][j]/I[i][j])² ≤ R[i]²—in other words, the magnitude of your voltage-to-current ratio is less than or equal to your resistance value. Your formula for capacitance assumes this ratio is larger than R, so when it's not, the math breaks down.
Additional Edge Case to Watch For
You should also check if I[i][j] is 0 (or very close to 0). Dividing by 0 will result in Infinity, which when squared stays Infinity, but this will still lead to unexpected results (like C[i][j] being 0) that you probably don't want.
Step-by-Step Fixes
Let's modify your C() method to handle these issues gracefully:
- Add validation for the square root term to catch negative values and log an error.
- Check for zero current to avoid division by zero.
- (Optional but recommended) Use
Math.PIinstead of your hardcodedpi=3.1415for more accurate calculations.
Here's the updated C() method:
public void C() { for(int i=0; i<2; i++) { for(int j=0; j<4; j++) { // Check for zero current first if (I[i][j] == 0) { System.err.println("Error: Current I[" + i + "][" + j + "] is zero! Cannot calculate capacitance."); C[i][j] = Double.NaN; continue; } // Calculate the term inside the square root double uiRatioSquared = Math.pow(U[i][j]/I[i][j], 2); // Simplified from pow(U,2)/pow(I,2) double rSquared = Math.pow(R[i], 2); double sqrtTerm = uiRatioSquared - rSquared; // Validate the square root term if (sqrtTerm < 0) { System.err.println("Error: sqrtTerm is negative at i=" + i + ", j=" + j + ". (U/I)² = " + uiRatioSquared + ", R² = " + rSquared); C[i][j] = Double.NaN; continue; } // Calculate capacitance with accurate PI value C[i][j] = 2 * Math.PI * f[i] * Math.sqrt(sqrtTerm); C[i][j] = Math.pow(C[i][j], -1); // Equivalent to 1/C[i][j] System.out.println("C"+i+","+j+"="+C[i][j]); } } }
What This Does
- It first checks if current is zero and alerts you to invalid input.
- It calculates the square root term separately and checks if it's negative, logging exactly which index has the problem and why.
- It simplifies
Math.pow(U[i][j],2)/Math.pow(I[i][j],2)toMath.pow(U[i][j]/I[i][j], 2)for cleaner code. - Uses
Math.PIfor more precise calculations than your hardcoded3.1415.
Next Steps
Run the updated code and check the error messages in the console. They'll tell you exactly which inputs are causing the issue—you can then either correct those input values or adjust your formula if you need to handle cases where (U/I)² ≤ R².
内容的提问来源于stack exchange,提问作者Jacenty Mateusz

