Implementing XOR with Fuzzy Logic in Python
Python Code from Grok
import numpy as np # Not strictly needed here, but kept for consistency
# Membership functions: simple linear for crisp 0/1 behavior
def membership_low(x):
"""Degree to which x belongs to 'Low' (0)"""
return max(0.0, min(1.0, 1.0 - x)) # Clips to [0,1]
def membership_high(x):
"""Degree to which x belongs to 'High' (1)"""
return max(0.0, min(1.0, x))
# Fuzzy XOR using Mamdani-style inference
def fuzzy_xor(a, b):
# Fuzzification
low_a = membership_low(a)
high_a = membership_high(a)
low_b = membership_low(b)
high_b = membership_high(b)
# Fuzzy rules for XOR:
# 1. If A is Low and B is Low → Output Low
# 2. If A is Low and B is High → Output High
# 3. If A is High and B is Low → Output High
# 4. If A is High and B is High → Output Low
rule1 = min(low_a, low_b) # → Low
rule2 = min(low_a, high_b) # → High
rule3 = min(high_a, low_b) # → High
rule4 = min(high_a, high_b) # → Low
# Aggregation: collect strength for Low and High output
strength_low = max(rule1, rule4)
strength_high = max(rule2, rule3)
# Defuzzification: center of gravity (centroids at 0 and 1)
total = strength_low + strength_high
if total == 0:
return 0.5 # Neutral (shouldn't happen with valid inputs)
output = (strength_low * 0 + strength_high * 1) / total
return output
# Display results on standard XOR training data
print("Fuzzy Logic XOR - Results on training data:")
print("-" * 50)
training_inputs = [[0, 0], [0, 1], [1, 0], [1, 1]]
expected_outputs = [0, 1, 1, 0]
for inp, expected in zip(training_inputs, expected_outputs):
result = fuzzy_xor(inp[0], inp[1])
print(f"Input: {inp} → Output: {result:.3f} (expected: {expected})")
print("\n" + "="*60)
print(" Interactive Fuzzy XOR Tester")
print(" Enter two numbers (0 or 1 recommended, but any real value works)")
print("="*60)
# Interactive loop for user input
while True:
try:
print("\nEnter two inputs separated by space (or type 'quit' to exit):")
user_input = input("> ").strip()
if user_input.lower() in ['quit', 'exit', 'q', '']:
print("Goodbye!")
break
parts = user_input.split()
if len(parts) != 2:
print("Error: Please enter exactly two numbers.")
continue
try:
a = float(parts[0])
b = float(parts[1])
except ValueError:
print("Error: Invalid numbers. Please enter numeric values.")
continue
# Compute fuzzy XOR
prediction = fuzzy_xor(a, b)
binary_prediction = 1 if prediction >= 0.5 else 0
# Classic boolean XOR for comparison (using threshold 0.5)
classic_xor = 1 if (a > 0.5) != (b > 0.5) else 0
print(f"\nInput: [{a}, {b}]")
print(f"Fuzzy output: {prediction:.4f}")
print(f"Rounded class: {binary_prediction}")
print(f"Classic XOR: {classic_xor} (for reference, using >0.5 threshold)")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
print(f"Unexpected error: {e}")