Demorgan’s Theorem Calculator

De Morgan's Theorem Calculator & Explanation :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –border-color: #ddd; –card-background: #fff; –shadow: 0 2px 5px rgba(0,0,0,0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; padding-bottom: 50px; } .container { width: 95%; max-width: 960px; margin: 20px auto; background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: var(–shadow); text-align: center; } h1, h2, h3 { color: var(–primary-color); margin-bottom: 20px; } h1 { font-size: 2.5em; } h2 { font-size: 1.8em; border-bottom: 2px solid var(–primary-color); padding-bottom: 10px; margin-top: 40px; } h3 { font-size: 1.4em; margin-top: 30px; } .calculator-wrapper { background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: var(–shadow); margin-bottom: 40px; } .loan-calc-container { display: flex; flex-direction: column; gap: 20px; align-items: center; } .input-group { width: 100%; max-width: 400px; text-align: left; margin-bottom: 15px; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: var(–primary-color); } .input-group input[type="text"], .input-group input[type="number"], .input-group select { width: calc(100% – 22px); padding: 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1em; box-sizing: border-box; } .input-group select { cursor: pointer; } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 5px; display: block; } .error-message { color: red; font-size: 0.8em; margin-top: 5px; height: 1.2em; } .button-group { display: flex; justify-content: center; gap: 15px; margin-top: 25px; flex-wrap: wrap; } button { padding: 12px 25px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background-color 0.3s ease; } button.primary { background-color: var(–primary-color); color: white; } button.primary:hover { background-color: #003366; } button.secondary { background-color: #6c757d; color: white; } button.secondary:hover { background-color: #5a6268; } button.reset { background-color: #ffc107; color: #212529; } button.reset:hover { background-color: #e0a800; } .results-container { margin-top: 30px; padding: 25px; background-color: #eef7ff; border: 1px solid #cce5ff; border-radius: 8px; text-align: left; } .results-container h3 { margin-top: 0; color: var(–primary-color); text-align: center; } .main-result { font-size: 2em; font-weight: bold; color: var(–success-color); background-color: #d4edda; padding: 15px; border-radius: 5px; margin-bottom: 20px; text-align: center; word-break: break-all; } .intermediate-results div, .formula-explanation div { margin-bottom: 10px; font-size: 0.95em; } .intermediate-results span, .formula-explanation span { font-weight: bold; color: var(–primary-color); } .formula-explanation { margin-top: 20px; padding-top: 15px; border-top: 1px dashed var(–border-color); font-style: italic; color: #555; } table { width: 100%; border-collapse: collapse; margin-top: 20px; box-shadow: var(–shadow); } th, td { padding: 12px 15px; border: 1px solid var(–border-color); text-align: left; } th { background-color: var(–primary-color); color: white; font-weight: bold; } td { background-color: var(–card-background); } tr:nth-child(even) td { background-color: #f2f2f2; } caption { font-size: 0.9em; color: #666; margin-bottom: 10px; font-style: italic; } canvas { margin-top: 30px; border: 1px solid var(–border-color); border-radius: 4px; background-color: var(–card-background); box-shadow: var(–shadow); } .article-content { width: 95%; max-width: 960px; margin: 20px auto; background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: var(–shadow); text-align: left; } .article-content p, .article-content ul, .article-content ol { margin-bottom: 20px; font-size: 1.05em; } .article-content li { margin-bottom: 10px; } .article-content a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .article-content a:hover { text-decoration: underline; } .faq-item { margin-bottom: 20px; padding: 15px; background-color: #fdfdfd; border: 1px solid #eee; border-radius: 5px; } .faq-item h4 { margin-top: 0; margin-bottom: 10px; color: var(–primary-color); font-size: 1.1em; cursor: pointer; } .faq-item p { margin-bottom: 0; display: none; /* Hidden by default */ } .faq-item.open p { display: block; } .related-links ul { list-style: none; padding: 0; } .related-links li { margin-bottom: 15px; } .related-links a { font-weight: bold; } .related-links span { font-size: 0.9em; color: #555; display: block; margin-top: 5px; } @media (max-width: 768px) { h1 { font-size: 2em; } h2 { font-size: 1.5em; } .container, .calculator-wrapper, .article-content { padding: 20px; } button { width: 100%; margin-bottom: 10px; } .button-group { flex-direction: column; align-items: center; } .main-result { font-size: 1.6em; } }

De Morgan's Theorem Calculator

Simplify and verify logical expressions using De Morgan's laws. Understand the equivalences between negations of conjunctions and disjunctions.

Enter a logical expression using AND (&), OR (|), NOT (!), and parentheses. Variables should be single uppercase letters.
Enter the equivalent expression to verify.

Verification Results

Enter expressions to verify.
De Morgan's Laws:
¬(P ∧ Q) ≡ (¬P) ∨ (¬Q)
¬(P ∨ Q) ≡ (¬P) ∧ (¬Q)

These laws state that the negation of a conjunction (AND) is the disjunction (OR) of the negations, and the negation of a disjunction (OR) is the conjunction (AND) of the negations.

Truth Table Visualization

Truth Table

Variables Expression 1 Expression 2 Equivalence

What is De Morgan's Theorem?

De Morgan's Theorem, named after the mathematician Augustus De Morgan, is a fundamental principle in formal logic and set theory. It provides a way to simplify or rewrite logical expressions by relating the negation of a conjunction (AND) to the disjunction (OR) of negations, and vice versa. Essentially, it tells us how to distribute a negation sign across an AND or an OR operation.

Who should use it? This theorem is crucial for anyone working with Boolean algebra, digital logic design, computer science (especially in programming and database queries), and formal logic. Programmers use it to simplify complex conditional statements, circuit designers use it to optimize logic gates, and mathematicians use it for formal proofs and set manipulations. Understanding De Morgan's Theorem can lead to more concise, efficient, and understandable logical structures.

Common misconceptions: A frequent misunderstanding is that De Morgan's Theorem only applies to simple negations. However, it's a powerful tool for simplifying nested negations and complex logical combinations. Another misconception is that the theorem is difficult to grasp; in reality, its core idea is quite intuitive once visualized with examples. People sometimes confuse the direction of the equivalence, thinking ¬(P ∧ Q) is equivalent to ¬P ∧ ¬Q, which is incorrect.

De Morgan's Theorem Formula and Mathematical Explanation

De Morgan's Theorem provides two key equivalences:

  1. The negation of a conjunction is the disjunction of the negations:
    ¬(P ∧ Q) ≡ (¬P) ∨ (¬Q)
  2. The negation of a disjunction is the conjunction of the negations:
    ¬(P ∨ Q) ≡ (¬P) ∧ (¬Q)

Let's break down the variables and their meanings:

Variable Definitions
Variable Meaning Unit Typical Range
P, Q Propositional variables (statements that can be either true or false) Boolean (True/False) {True, False}
¬ (or !) Logical NOT (negation) Operator Applies to a single proposition
∧ (or &) Logical AND (conjunction) Operator Requires two propositions
∨ (or |) Logical OR (disjunction) Operator Requires two propositions
Logical Equivalence Operator Indicates that two expressions always have the same truth value

Derivation using Truth Tables: The most straightforward way to prove De Morgan's Theorem is by constructing truth tables. We show that for all possible truth values of the involved propositions, the left-hand side (LHS) of the equivalence always yields the same truth value as the right-hand side (RHS).

Example Derivation for ¬(P ∧ Q) ≡ (¬P) ∨ (¬Q):

Truth Table for ¬(P ∧ Q) ≡ (¬P) ∨ (¬Q)
P Q P ∧ Q ¬(P ∧ Q) ¬P ¬Q (¬P) ∨ (¬Q) Equivalence
T T T F F F F T
T F F T F T T T
F T F T T F T T
F F F T T T T T

As the columns for ¬(P ∧ Q) and (¬P) ∨ (¬Q) are identical, the equivalence holds true. A similar truth table can be constructed for the second law, ¬(P ∨ Q) ≡ (¬P) ∧ (¬Q).

Practical Examples (Real-World Use Cases)

De Morgan's Theorem is surprisingly practical in everyday logic and programming.

Example 1: Simplifying a Condition in Code

Imagine a program that needs to check if a user is NOT logged in AND has not accepted the terms. The condition might be written as: `if (!(isLoggedIn & hasAcceptedTerms))`. This is logically correct but can be confusing. Applying De Morgan's Theorem, we can rewrite this as: `if (!isLoggedIn | !hasAcceptedTerms)`. This translates to: "If the user is NOT logged in OR the user has NOT accepted the terms." This revised condition is often easier to read and understand, making the code more maintainable.

Inputs:

  • Expression 1: `!(isLoggedIn & hasAcceptedTerms)`
  • Expression 2: `!isLoggedIn | !hasAcceptedTerms`

Calculator Output: The calculator would confirm these are equivalent, showing 'True' for the main result and potentially breaking down the truth values for `isLoggedIn` and `hasAcceptedTerms` being True/False.

Financial Interpretation: In a financial application, this could relate to user access. If a user needs to be logged in AND have accepted terms to access certain features, the negation means they are blocked if EITHER they are not logged in OR they haven't accepted terms. This ensures security and compliance.

Example 2: Database Query Optimization

Consider searching a database for customers who are NOT (from California AND have made a purchase over $1000). A naive query might be complex. Using De Morgan's Theorem, we can express this as: Customers who are (NOT from California) OR (have NOT made a purchase over $1000).

Inputs:

  • Expression 1: `!(state = 'CA' & purchaseAmount > 1000)`
  • Expression 2: `state != 'CA' | purchaseAmount <= 1000`

Calculator Output: The calculator verifies the logical equivalence.

Financial Interpretation: This allows for more efficient database queries. Instead of searching for a complex negative condition, you can search for customers who either reside outside California OR whose purchase history doesn't meet the high-value threshold. This can significantly speed up data retrieval for marketing or analysis.

How to Use This De Morgan's Theorem Calculator

Our De Morgan's Theorem Calculator is designed for simplicity and clarity. Follow these steps to verify logical equivalences:

  1. Enter Expression 1: In the first input field ("Expression 1"), type your initial logical expression. Use standard logical operators: `!` for NOT, `&` for AND, `|` for OR. Use parentheses `()` to define the order of operations. Variables should be single uppercase letters (e.g., `A`, `B`, `C`). Example: `!(A & B)`.
  2. Enter Expression 2: In the second input field ("Expression 2"), type the expression you believe is equivalent to Expression 1. Use the same syntax. Example: `!A | !B`.
  3. Verify Equivalence: Click the "Verify Equivalence" button.
  4. Read the Results:
    • Main Result: A prominent message will indicate whether the two expressions are "Equivalent" or "Not Equivalent".
    • Intermediate Values: The calculator shows the truth values for each expression under different variable assignments, helping you pinpoint where differences might occur if they are not equivalent.
    • Truth Table: A detailed truth table lists all possible combinations of variable truth values and shows the resulting truth value for both Expression 1 and Expression 2, along with a final column confirming equivalence for each row.
    • Truth Table Visualization: The chart provides a visual representation of the truth table, making it easier to compare the outcomes of the two expressions across all scenarios.
  5. Decision-Making Guidance: If the expressions are equivalent, you can confidently replace one with the other, often choosing the simpler form for clarity or efficiency. If they are not equivalent, it highlights a misunderstanding or error in the logical formulation.
  6. Copy Results: Use the "Copy Results" button to save the main finding, intermediate values, and key assumptions (like the specific laws used) for documentation or sharing.
  7. Reset: Click "Reset" to clear all fields and start a new verification.

Key Factors Affecting Logical Equivalence

While De Morgan's Theorem itself is a fixed mathematical principle, the application and interpretation of logical expressions can be influenced by several factors:

  1. Correct Operator Usage: Ensuring the correct symbols for AND (`&`), OR (`|`), and NOT (`!`) are used is paramount. Misusing operators leads to incorrect expressions and invalid conclusions.
  2. Parentheses and Order of Operations: Like in arithmetic, the order of operations matters in logic. Incorrectly placed parentheses can drastically change the meaning of an expression. De Morgan's laws specifically deal with how negation interacts with AND/OR, so understanding the scope of the negation is key.
  3. Variable Definitions: The truth value of propositions (variables) must be clearly defined. In programming, these might be boolean flags; in formal logic, they are statements. Ambiguity here leads to flawed analysis.
  4. Scope of Negation: De Morgan's Theorem is all about distributing negation. Understanding exactly what the negation applies to (a single variable, an AND expression, an OR expression) is critical for correct application. `!A & B` is different from `!(A & B)`.
  5. Completeness of Truth Table: For a theorem to hold, it must be true for ALL possible combinations of input variable truth values. Our calculator generates a full truth table to ensure this comprehensive verification. Missing cases can lead to false assumptions of equivalence.
  6. Context of Application: While the mathematical theorem is universal, its practical application (e.g., in code or circuit design) depends on the specific context. The *meaning* of `A` and `B` in a financial system might differ from their meaning in a physics simulation, but the logical equivalence provided by De Morgan's Theorem remains constant.

Frequently Asked Questions (FAQ)

What are the two main forms of De Morgan's Theorem?

The two main forms are: ¬(P ∧ Q) ≡ (¬P) ∨ (¬Q) and ¬(P ∨ Q) ≡ (¬P) ∧ (¬Q). They describe how to negate AND and OR operations.

Can De Morgan's Theorem be applied to more than two variables?

Yes, it can be extended. For example, ¬(P ∧ Q ∧ R) ≡ (¬P) ∨ (¬Q) ∨ (¬R). The principle remains the same: negate each variable and flip the operator.

How is this theorem used in programming?

It's used to simplify complex conditional statements (if/else conditions), making code more readable and sometimes more efficient. For instance, simplifying `if (!(userIsAdmin & hasPermission))` to `if (!userIsAdmin | !hasPermission)`.

What does the '≡' symbol mean?

The symbol '≡' denotes logical equivalence. It means that the expressions on both sides of the symbol will always have the same truth value for all possible assignments of truth values to their variables.

Is De Morgan's Theorem applicable to set theory?

Yes, it has direct parallels in set theory. The complement of an intersection is the union of the complements: (A ∩ B)' = A' ∪ B'. Similarly, the complement of a union is the intersection of the complements: (A ∪ B)' = A' ∩ B'.

What happens if I enter invalid characters or syntax?

The calculator will likely show an error message or fail to produce meaningful results. It's designed for standard logical operators (&, |, !) and uppercase letter variables, along with parentheses.

Can the calculator handle nested expressions?

Yes, the underlying logic attempts to parse and evaluate nested expressions correctly, respecting parentheses. For example, `!((A & B) | C)`.

Why is understanding logical equivalence important in finance?

In financial modeling, risk assessment, or algorithmic trading, logical conditions determine outcomes. Simplifying these conditions using De Morgan's Theorem can lead to clearer, more robust algorithms and prevent errors in complex decision-making processes.

© 2023 De Morgan's Theorem Calculator. All rights reserved.

function isValidLogicalExpression(expr) { if (!expr) return false; // Basic check: allows uppercase letters, !, &, |, (, ), spaces return /^[A-Z\s!&|()]+$/.test(expr); } function parseExpression(expr, variables) { var evaluated = {}; var tempExpr = expr.replace(/AND/gi, '&').replace(/OR/gi, '|').replace(/NOT/gi, '!'); tempExpr = tempExpr.replace(/\s+/g, "); // Remove all whitespace var variableSet = new Set(); for (var i = 0; i = 'A' && tempExpr[i] <= 'Z') { variableSet.add(tempExpr[i]); } } var sortedVars = Array.from(variableSet).sort(); variables.length = 0; // Clear existing variables variables.push(…sortedVars); var truthTable = []; var numVars = variables.length; var numRows = 1 << numVars; // 2^numVars for (var i = 0; i < numRows; i++) { var row = {}; var currentValues = {}; for (var j = 0; j > (numVars – 1 – j)) & 1) === 1; row[variables[j]] = value; currentValues[variables[j]] = value; } try { var result = evaluateLogicalExpression(tempExpr, currentValues); row.result = result; truthTable.push(row); } catch (e) { console.error("Error evaluating expression segment:", e); // Handle cases where evaluation might fail due to syntax or logic row.result = null; // Indicate error truthTable.push(row); } } return truthTable; } function evaluateLogicalExpression(expr, values) { var evalExpr = expr; // Replace variable names with their boolean values for (var variable in values) { var regex = new RegExp(variable, 'g'); evalExpr = evalExpr.replace(regex, values[variable]); } // Replace operators with JavaScript equivalents evalExpr = evalExpr.replace(/!/g, '!'); evalExpr = evalExpr.replace(/&/g, '&&'); evalExpr = evalExpr.replace(/\|/g, '||'); // Use Function constructor for evaluation (use with caution, but suitable here) // This is a simplified approach; a full parser would be more robust. try { // Need to handle operator precedence carefully. // A simple eval might not work directly for complex logic. // Let's implement a basic recursive descent parser or similar logic. // For simplicity and demonstration, let's try a direct eval after careful replacement. // This requires ensuring the expression is well-formed and operators are correctly mapped. // A more robust approach involves tokenizing and parsing. // For this example, we'll rely on a simplified eval after operator mapping. // Let's refine the operator mapping and structure for eval. // We need to handle parentheses correctly. // A simplified approach for common cases: // Replace !true with false, !false with true // Replace true & true with true, etc. // Let's use a helper function that handles precedence. return evaluateWithPrecedence(evalExpr, values); } catch (e) { console.error("Evaluation error:", e); throw new Error("Invalid expression format or evaluation error."); } } // Simplified evaluation function considering precedence function evaluateWithPrecedence(expr, values) { // Replace variables with values var processedExpr = expr; for (var v in values) { var regex = new RegExp('\\b' + v + '\\b', 'g'); // Use word boundaries processedExpr = processedExpr.replace(regex, values[v]); } // Replace operators with JS equivalents processedExpr = processedExpr.replace(/!/g, '!'); processedExpr = processedExpr.replace(/&/g, '&&'); processedExpr = processedExpr.replace(/\|/g, '||'); // Handle NOT operations first (unary) processedExpr = processedExpr.replace(/!true/g, 'false'); processedExpr = processedExpr.replace(/!false/g, 'true'); // Now, evaluate the rest using eval (carefully) // This is still a simplification. A full parser is ideal. try { // Ensure boolean context for eval var result = eval(processedExpr); return !!result; // Ensure boolean return } catch (e) { console.error("Eval error:", e, "Expression:", processedExpr); throw new Error("Syntax error in expression."); } } function getVariables(expr) { var vars = new Set(); for (var i = 0; i = 'A' && expr[i] <= 'Z') { vars.add(expr[i]); } } return Array.from(vars).sort(); } function generateTruthTable(expr1, expr2) { var variables1 = getVariables(expr1); var variables2 = getVariables(expr2); var allVars = Array.from(new Set([…variables1, …variables2])).sort(); var tableBody = document.querySelector("#truthTable tbody"); tableBody.innerHTML = ''; // Clear previous rows var numVars = allVars.length; var numRows = 1 << numVars; var results1 = []; var results2 = []; for (var i = 0; i < numRows; i++) { var rowData = {}; var currentValues = {}; var varValuesStr = []; for (var j = 0; j > (numVars – 1 – j)) & 1) === 1; currentValues[allVars[j]] = value; varValuesStr.push(allVars[j] + "=" + (value ? "T" : "F")); } var expr1Result = null; var expr2Result = null; var equivalence = "N/A"; try { expr1Result = evaluateLogicalExpression(expr1, currentValues); results1.push(expr1Result); } catch (e) { results1.push(null); // Indicate error } try { expr2Result = evaluateLogicalExpression(expr2, currentValues); results2.push(expr2Result); } catch (e) { results2.push(null); // Indicate error } if (expr1Result !== null && expr2Result !== null) { equivalence = (expr1Result === expr2Result) ? "T" : "F"; } else { equivalence = "Error"; } var tr = document.createElement("tr"); var tdVars = document.createElement("td"); tdVars.textContent = varValuesStr.join(", "); tr.appendChild(tdVars); var tdExpr1 = document.createElement("td"); tdExpr1.textContent = expr1Result === null ? "Error" : (expr1Result ? "T" : "F"); tr.appendChild(tdExpr1); var tdExpr2 = document.createElement("td"); tdExpr2.textContent = expr2Result === null ? "Error" : (expr2Result ? "T" : "F"); tr.appendChild(tdExpr2); var tdEquiv = document.createElement("td"); tdEquiv.textContent = equivalence; tr.appendChild(tdEquiv); tableBody.appendChild(tr); } return { allVars, results1, results2 }; } function updateChart(allVars, results1, results2) { var canvas = document.getElementById('truthTableChart'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous chart var numRows = results1.length; if (numRows === 0) return; var chartHeight = 300; var chartWidth = canvas.width – 40; // Account for padding var barWidth = (chartWidth / numRows) * 0.8; var barSpacing = (chartWidth / numRows) * 0.2; var maxValue = 1; // Boolean values are 0 or 1 var scaleY = (chartHeight – 40) / maxValue; // -40 for top padding // Draw axes ctx.strokeStyle = '#ccc'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(20, chartHeight – 20); // X-axis start ctx.lineTo(chartWidth + 20, chartHeight – 20); // X-axis end ctx.moveTo(20, chartHeight – 20); // Y-axis start ctx.lineTo(20, 20); // Y-axis end ctx.stroke(); // Draw labels and bars for Expression 1 ctx.fillStyle = 'rgba(0, 74, 153, 0.7)'; // Primary color var xPos = 30; for (var i = 0; i < numRows; i++) { var height = results1[i] === null ? 0 : (results1[i] ? chartHeight – 20 – (scaleY * 1) : chartHeight – 20 – (scaleY * 0)); ctx.fillRect(xPos, height, barWidth * 0.4, chartHeight – 20 – height); // Draw label for row (e.g., A=T, B=F) var rowLabel = ""; var currentValues = {}; for (var j = 0; j > (allVars.length – 1 – j)) & 1) === 1; currentValues[allVars[j]] = value; rowLabel += allVars[j] + "=" + (value ? "T" : "F") + " "; } ctx.fillStyle = '#333′; ctx.font = '10px Arial'; ctx.textAlign = 'center'; ctx.fillText(rowLabel.trim(), xPos + barWidth * 0.4 / 2, chartHeight – 5); xPos += barWidth * 0.4 + barSpacing; } // Draw bars for Expression 2 ctx.fillStyle = 'rgba(40, 167, 69, 0.7)'; // Success color xPos = 30 + barWidth * 0.4 + barSpacing; // Offset for second series for (var i = 0; i < numRows; i++) { var height = results2[i] === null ? 0 : (results2[i] ? chartHeight – 20 – (scaleY * 1) : chartHeight – 20 – (scaleY * 0)); ctx.fillRect(xPos, height, barWidth * 0.4, chartHeight – 20 – height); xPos += barWidth * 0.4 + barSpacing; } // Add legend var legendHtml = '
'; legendHtml += 'Expression 1'; legendHtml += 'Expression 2'; legendHtml += '
'; document.getElementById('chartLegend').innerHTML = legendHtml; } function calculateDeMorgan() { var expr1Input = document.getElementById('expression1'); var expr2Input = document.getElementById('expression2'); var expr1Error = document.getElementById('expression1Error'); var expr2Error = document.getElementById('expression2Error'); var mainResult = document.getElementById('mainResult'); var intermediate1 = document.getElementById('intermediate1'); var intermediate2 = document.getElementById('intermediate2'); var intermediate3 = document.getElementById('intermediate3'); var expr1 = expr1Input.value.trim(); var expr2 = expr2Input.value.trim(); expr1Error.textContent = "; expr2Error.textContent = "; if (!expr1 || !expr2) { mainResult.textContent = "Please enter both expressions."; mainResult.style.color = 'orange'; return; } if (!isValidLogicalExpression(expr1)) { expr1Error.textContent = "Invalid characters or format in Expression 1."; return; } if (!isValidLogicalExpression(expr2)) { expr2Error.textContent = "Invalid characters or format in Expression 2."; return; } var variables1 = getVariables(expr1); var variables2 = getVariables(expr2); var allVars = Array.from(new Set([…variables1, …variables2])).sort(); if (allVars.length === 0) { mainResult.textContent = "No variables found in expressions."; mainResult.style.color = 'orange'; return; } var truthTableData = generateTruthTable(expr1, expr2); var { allVars: chartVars, results1, results2 } = truthTableData; var isEquivalent = true; var errorOccurred = false; for (var i = 0; i < results1.length; i++) { if (results1[i] === null || results2[i] === null) { errorOccurred = true; break; } if (results1[i] !== results2[i]) { isEquivalent = false; break; } } if (errorOccurred) { mainResult.textContent = "Error evaluating expressions. Check syntax."; mainResult.style.color = 'red'; intermediate1.innerHTML = ''; intermediate2.innerHTML = ''; intermediate3.innerHTML = ''; } else { mainResult.textContent = isEquivalent ? "Equivalent" : "Not Equivalent"; mainResult.style.color = isEquivalent ? 'var(–success-color)' : 'red'; intermediate1.innerHTML = "Variables Considered: " + chartVars.join(', '); intermediate2.innerHTML = "Number of Rows: " + (1 << chartVars.length); intermediate3.innerHTML = "Equivalence Holds: " + (isEquivalent ? "True for all cases" : "False for at least one case"); updateChart(chartVars, results1, results2); } } function resetCalculator() { document.getElementById('expression1').value = '!(A & B)'; document.getElementById('expression2').value = '!A | !B'; document.getElementById('expression1Error').textContent = "; document.getElementById('expression2Error').textContent = "; document.getElementById('mainResult').textContent = 'Enter expressions to verify.'; document.getElementById('mainResult').style.color = 'var(–text-color)'; document.getElementById('intermediate1').innerHTML = "; document.getElementById('intermediate2').innerHTML = "; document.getElementById('intermediate3').innerHTML = "; var canvas = document.getElementById('truthTableChart'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); document.getElementById('chartLegend').innerHTML = "; document.querySelector("#truthTable tbody").innerHTML = "; } function copyResults() { var expr1 = document.getElementById('expression1').value; var expr2 = document.getElementById('expression2').value; var mainResult = document.getElementById('mainResult').textContent; var intermediate1 = document.getElementById('intermediate1').textContent; var intermediate2 = document.getElementById('intermediate2').textContent; var intermediate3 = document.getElementById('intermediate3').textContent; var formulaExplanation = document.querySelector('.formula-explanation').innerText.replace('De Morgan\'s Laws:', 'De Morgan\'s Laws:\n¬(P ∧ Q) ≡ (¬P) ∨ (¬Q)\n¬(P ∨ Q) ≡ (¬P) ∧ (¬Q)\n'); var textToCopy = `De Morgan's Theorem Verification Results:\n\n`; textToCopy += `Expression 1: ${expr1}\n`; textToCopy += `Expression 2: ${expr2}\n\n`; textToCopy += `Verification Status: ${mainResult}\n\n`; textToCopy += `Details:\n${intermediate1}\n${intermediate2}\n${intermediate3}\n\n`; textToCopy += `Key Assumptions:\n${formulaExplanation}\n`; // Use navigator.clipboard for modern browsers if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(textToCopy).then(function() { alert('Results copied to clipboard!'); }).catch(function(err) { console.error('Failed to copy text: ', err); fallbackCopyTextToClipboard(textToCopy); }); } else { fallbackCopyTextToClipboard(textToCopy); } } function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position = "fixed"; // Avoid scrolling to bottom textArea.style.left = "-9999px"; textArea.style.top = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'Results copied to clipboard!' : 'Failed to copy results.'; alert(msg); } catch (err) { console.error('Fallback: Oops, unable to copy', err); alert('Failed to copy results.'); } document.body.removeChild(textArea); } function toggleFaq(element) { var content = element.nextElementSibling; var faqItem = element.closest('.faq-item'); if (content.style.display === "block") { content.style.display = "none"; faqItem.classList.remove('open'); } else { content.style.display = "block"; faqItem.classList.add('open'); } } // Initialize calculator on load document.addEventListener('DOMContentLoaded', function() { resetCalculator(); // Set default values // Initial calculation for default values calculateDeMorgan(); });

Leave a Comment