// target equation: Z = √(R^2 + (X_L - X_C)^2) var xl = 0; // constant var xc = 0; // constant var r = new Array(); // independent variable var z = new Array(); // dependent variable function calcZ(r, xl, xc) { var x = xl - xc; // (X_L - X_C) var temp = r * r + x * x; // (R^2 + (X_L - X_C)^2) return Math.sqrt(temp); } function calculate() { xl = Number($("#xl").val()); xc = Number($("#xc").val()); var minr = Number($("#minr").val()); var maxr = Number($("#maxr").val()); var rval = 0; var valid = true; valid = validDeci(xl, "XL"); valid = validDeci(xc, "XC"); valid = validWhole(minr, "R's minimum"); valid = validWhole(maxr, "R's maximum"); if (maxr < minr) { //extra check, are the boundaries valid? valid = false; alert("The maximum cannot be less than the minimum!"); } if (!valid) { return false; } var i = 0 for (rval = minr; rval <= maxr; rval++) { r[i] = rval; z[i] = calcZ(rval, xl, xc); i++; } return true; } function validDeci(entry, label) { if (entry == "" || entry == null) { alert("Please enter a value for " + label + ".") return false; } if (/^\d+\.?\d*$/.test(entry)) { if (/\.{0,3}/) { // separated to provide more specific error messages return true; } else { alert("Please round " + label + " to 3 places and try again."); return false; } } else { alert("Please enter a numeric value for " + label + " and try again."); return false; } } function validWhole(entry, label) { // The max and min should be whole. if (entry == "" || entry == null) { alert("Please enter a value for " + label + ".") return false; } if (/^\d+$/.test(entry)) { return true; } else { alert(label + " must be a whole number. Please try again."); return false; } } function display() { var s = ""; var match = false; s = "Z = √((R)2 + (" + xl + " - " + xc + ")2
)"; for (var i = 0; i < r.length; i++) { s += "When R = " + r[i] + ", Z = " + z[i].toFixed(3) + "
"; if (r[i] == (xl - xc)) { match = true; } } if (match == true) { // explains the topic further if the user set R correctly s += "You might have noticed that the formula for Z is simply the Pythagorean theorem. " + "R, X, and Z can be represented as sides of a right triangle, so when R = X, Z is always equal to R√2. "; } values.innerHTML = s; } function plotVals() { var trace1 = { x: r, y: z, mode: "scatter", name: "Resistance (R)", } var data = [trace1] var layout = { title: "Effect of Resistance on Impedance", showlegend: true, width: 500, height: 500, paper_bgcolor: "#c4ffa7", plot_bgcolor: "#97EB9E", xaxis: { title: "R (ohms)", }, yaxis: { title: "Z (ohms)", }, } Plotly.newPlot("container", data, layout, {displayModeBar: false}); } $(document).ready(function() { $("#calc").click(function () { if (calculate()) { display(); } }) $("#plot").click(function () { if (calculate()) { plotVals(); } })})