Numero_Complesso

Risposta di Claude AI (semplificata)

import math

class ComplexNumber:
    def __init__(self, real = 0, imag = 0):
        self.real = float(real)
        self.imag = float(imag)
    
    def __str__(self):
        if self.imag == 0:
            return f"{self.real}"
        elif self.real == 0:
            return f"{self.imag}i"
        elif self.imag < 0:
            return f"{self.real} - {abs(self.imag)}i"
        else:
            return f"{self.real} + {self.imag}i"
    
    def __repr__(self):
        return f"ComplexNumber({self.real}, {self.imag})"
    
    def __add__(self, other):
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real + other, self.imag)
        return ComplexNumber(self.real + other.real, self.imag + other.imag)
    
    def __radd__(self, other):
        return self.__add__(other)
    
    def __sub__(self, other):
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real - other, self.imag)
        return ComplexNumber(self.real - other.real, self.imag - other.imag)
    
    def __rsub__(self, other):
        if isinstance(other, (int, float)):
            return ComplexNumber(other - self.real, -self.imag)
        return ComplexNumber(other.real - self.real, other.imag - self.imag)
    
    def __mul__(self, other):
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real * other, self.imag * other)
        real_part = self.real * other.real - self.imag * other.imag
        imag_part = self.real * other.imag + self.imag * other.real
        return ComplexNumber(real_part, imag_part)
    
    def __rmul__(self, other):
        return self.__mul__(other)
    
    def __truediv__(self, other):
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real / other, self.imag / other)
        denominator = other.real**2 + other.imag**2
        real_part = (self.real * other.real + self.imag * other.imag) / denominator
        imag_part = (self.imag * other.real - self.real * other.imag) / denominator
        return ComplexNumber(real_part, imag_part)
    
    def __rtruediv__(self, other):
        if isinstance(other, (int, float)):
            denominator = self.real**2 + self.imag**2
            real_part = other * self.real / denominator
            imag_part = -other * self.imag / denominator
            return ComplexNumber(real_part, imag_part)
    
    def __eq__(self, other):
        if isinstance(other, (int, float)):
            return self.real == other and self.imag == 0
        return self.real == other.real and self.imag == other.imag
    
    def __pow__(self, power):
        if not isinstance(power, (int, float)):
            raise ValueError("L'esponente deve essere un numero reale")      
        if power == 0:
            return ComplexNumber(1, 0)
        r = self.modulus()
        theta = self.phase()
        
        new_r = r ** power
        new_theta = theta * power
        
        real_part = new_r * math.cos(new_theta)
        imag_part = new_r * math.sin(new_theta)
        
        return ComplexNumber(real_part, imag_part)
    
    def conjugate(self):
        return ComplexNumber(self.real, -self.imag)
    
    def modulus(self):
        return math.sqrt(self.real**2 + self.imag**2)
    
    def phase(self):
        return math.atan2(self.imag, self.real)
    
    def to_polar(self):
        return (self.modulus(), self.phase())
    
    @staticmethod
    def from_polar(modulus, phase):
        real = modulus * math.cos(phase)
        imag = modulus * math.sin(phase)
        return ComplexNumber(real, imag)

# -------------------------------------------------------------- Funzioni di utilità

def solve_quadratic(a, b, c):
    discriminant = b**2 - 4*a*c   
    if discriminant >= 0:
        x1 = (-b + math.sqrt(discriminant)) / (2*a)
        x2 = (-b - math.sqrt(discriminant)) / (2*a)
        return ComplexNumber(x1), ComplexNumber(x2)
    else:
        real_part = -b / (2*a)
        imag_part = math.sqrt(abs(discriminant)) / (2*a)
        return ComplexNumber(real_part, imag_part), ComplexNumber(real_part, -imag_part)

def roots_of_unity(n):
    roots = []
    for k in range(n):
        angle = 2 * math.pi * k / n
        roots.append(ComplexNumber.from_polar(1, angle))
    return roots

# -------------------------------------------------------------- Esempio di utilizzo

if __name__ == "__main__":
    z1 = ComplexNumber(3, 4)
    z2 = ComplexNumber(1, -2)
    
    print(f"z1 = {z1}")
    print(f"z2 = {z2}")
    
    print(f"z1 + z2 = {z1 + z2}")
    print(f"z1 - z2 = {z1 - z2}")
    print(f"z1 * z2 = {z1 * z2}")
    print(f"z1 / z2 = {z1 / z2}")
    
    print(f"|z1| = {z1.modulus()}")
    print(f"Fase di z1 = {z1.phase()} radianti")
    
    print(f"Coniugato di z1 = {z1.conjugate()}")
    
    polar = z1.to_polar()
    print(f"z1 in forma polare = ({polar[0]}, {polar[1]})")
    
    print("Radici terze dell'unità:")
    for root in roots_of_unity(3):
        print(f"  {root}")
    
    print("Radici di x^2 + 1 = 0:")
    roots = solve_quadratic(1, 0, 1)
    print(f"  x1 = {roots[0]}")
    print(f"  x2 = {roots[1]}")

Versione originale

# complex_ops.py - Modulo per la gestione dei numeri complessi

import math
from typing import Union, Tuple, List

class ComplexNumber:
    """
    Classe per rappresentare e manipolare numeri complessi nella forma a + bi.
    """
    
    def __init__(self, real: float = 0, imag: float = 0):
        """
        Inizializza un numero complesso con parte reale e immaginaria.
        
        Args:
            real: La parte reale del numero complesso
            imag: La parte immaginaria del numero complesso
        """
        self.real = float(real)
        self.imag = float(imag)
    
    def __str__(self) -> str:
        """Restituisce la rappresentazione testuale del numero complesso."""
        if self.imag == 0:
            return f"{self.real}"
        elif self.real == 0:
            return f"{self.imag}i"
        elif self.imag < 0:
            return f"{self.real} - {abs(self.imag)}i"
        else:
            return f"{self.real} + {self.imag}i"
    
    def __repr__(self) -> str:
        """Restituisce la rappresentazione formale del numero complesso."""
        return f"ComplexNumber({self.real}, {self.imag})"
    
    def __add__(self, other):
        """Addizione tra numeri complessi."""
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real + other, self.imag)
        return ComplexNumber(self.real + other.real, self.imag + other.imag)
    
    def __radd__(self, other):
        """Addizione inversa tra numeri complessi."""
        return self.__add__(other)
    
    def __sub__(self, other):
        """Sottrazione tra numeri complessi."""
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real - other, self.imag)
        return ComplexNumber(self.real - other.real, self.imag - other.imag)
    
    def __rsub__(self, other):
        """Sottrazione inversa tra numeri complessi."""
        if isinstance(other, (int, float)):
            return ComplexNumber(other - self.real, -self.imag)
        return ComplexNumber(other.real - self.real, other.imag - self.imag)
    
    def __mul__(self, other):
        """Moltiplicazione tra numeri complessi."""
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real * other, self.imag * other)
        # (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
        real_part = self.real * other.real - self.imag * other.imag
        imag_part = self.real * other.imag + self.imag * other.real
        return ComplexNumber(real_part, imag_part)
    
    def __rmul__(self, other):
        """Moltiplicazione inversa tra numeri complessi."""
        return self.__mul__(other)
    
    def __truediv__(self, other):
        """Divisione tra numeri complessi."""
        if isinstance(other, (int, float)):
            return ComplexNumber(self.real / other, self.imag / other)
        # (a + bi) / (c + di) = ((ac + bd) + (bc - ad)i) / (c^2 + d^2)
        denominator = other.real**2 + other.imag**2
        real_part = (self.real * other.real + self.imag * other.imag) / denominator
        imag_part = (self.imag * other.real - self.real * other.imag) / denominator
        return ComplexNumber(real_part, imag_part)
    
    def __rtruediv__(self, other):
        """Divisione inversa tra numeri complessi."""
        if isinstance(other, (int, float)):
            # other / (a + bi) = other * (a - bi) / (a^2 + b^2)
            denominator = self.real**2 + self.imag**2
            real_part = other * self.real / denominator
            imag_part = -other * self.imag / denominator
            return ComplexNumber(real_part, imag_part)
    
    def __eq__(self, other):
        """Uguaglianza tra numeri complessi."""
        if isinstance(other, (int, float)):
            return self.real == other and self.imag == 0
        return self.real == other.real and self.imag == other.imag
    
    def __pow__(self, power):
        """Elevamento a potenza di un numero complesso."""
        if not isinstance(power, (int, float)):
            raise ValueError("L'esponente deve essere un numero reale")
        
        if power == 0:
            return ComplexNumber(1, 0)
        
        # Forma polare per potenze
        r = self.modulus()
        theta = self.phase()
        
        new_r = r ** power
        new_theta = theta * power
        
        real_part = new_r * math.cos(new_theta)
        imag_part = new_r * math.sin(new_theta)
        
        return ComplexNumber(real_part, imag_part)
    
    def conjugate(self):
        """Restituisce il coniugato del numero complesso (a + bi -> a - bi)."""
        return ComplexNumber(self.real, -self.imag)
    
    def modulus(self) -> float:
        """Restituisce il modulo del numero complesso (|a + bi| = sqrt(a^2 + b^2))."""
        return math.sqrt(self.real**2 + self.imag**2)
    
    def phase(self) -> float:
        """Restituisce la fase del numero complesso in radianti (arctan(b/a))."""
        return math.atan2(self.imag, self.real)
    
    def to_polar(self) -> Tuple[float, float]:
        """Converte il numero complesso in forma polare (r, θ)."""
        return (self.modulus(), self.phase())
    
    @staticmethod
    def from_polar(modulus: float, phase: float):
        """
        Crea un numero complesso dalla sua forma polare.
        
        Args:
            modulus: Modulo del numero complesso (r)
            phase: Fase del numero complesso in radianti (θ)
            
        Returns:
            Un nuovo oggetto ComplexNumber
        """
        real = modulus * math.cos(phase)
        imag = modulus * math.sin(phase)
        return ComplexNumber(real, imag)


# Funzioni di utilità
def solve_quadratic(a: float, b: float, c: float) -> Tuple[ComplexNumber, ComplexNumber]:
    """
    Risolve un'equazione quadratica ax^2 + bx + c = 0 e restituisce le radici.
    
    Returns:
        Una tupla contenente le due radici dell'equazione quadratica
    """
    discriminant = b**2 - 4*a*c
    
    if discriminant >= 0:
        x1 = (-b + math.sqrt(discriminant)) / (2*a)
        x2 = (-b - math.sqrt(discriminant)) / (2*a)
        return ComplexNumber(x1), ComplexNumber(x2)
    else:
        real_part = -b / (2*a)
        imag_part = math.sqrt(abs(discriminant)) / (2*a)
        return ComplexNumber(real_part, imag_part), ComplexNumber(real_part, -imag_part)

def roots_of_unity(n: int) -> List[ComplexNumber]:
    """
    Calcola le n radici n-esime dell'unità.
    
    Args:
        n: Il numero di radici da calcolare
        
    Returns:
        Una lista di oggetti ComplexNumber rappresentanti le radici n-esime dell'unità
    """
    roots = []
    for k in range(n):
        angle = 2 * math.pi * k / n
        roots.append(ComplexNumber.from_polar(1, angle))
    return roots


# Esempio di utilizzo
if __name__ == "__main__":
    # Creazione di numeri complessi
    z1 = ComplexNumber(3, 4)
    z2 = ComplexNumber(1, -2)
    
    print(f"z1 = {z1}")
    print(f"z2 = {z2}")
    
    # Operazioni aritmetiche
    print(f"z1 + z2 = {z1 + z2}")
    print(f"z1 - z2 = {z1 - z2}")
    print(f"z1 * z2 = {z1 * z2}")
    print(f"z1 / z2 = {z1 / z2}")
    
    # Modulo e fase
    print(f"|z1| = {z1.modulus()}")
    print(f"Fase di z1 = {z1.phase()} radianti")
    
    # Coniugato
    print(f"Coniugato di z1 = {z1.conjugate()}")
    
    # Conversione forma polare e cartesiana
    polar = z1.to_polar()
    print(f"z1 in forma polare = ({polar[0]}, {polar[1]})")
    
    # Radici di unità
    print("Radici terze dell'unità:")
    for root in roots_of_unity(3):
        print(f"  {root}")
    
    # Risoluzione equazione quadratica
    print("Radici di x^2 + 1 = 0:")
    roots = solve_quadratic(1, 0, 1)
    print(f"  x1 = {roots[0]}")
    print(f"  x2 = {roots[1]}")