Questo è il codice che uso (trovato sui forum):
Codice PHP:
<?php
function solve($eq) {
if($eq == null || $eq == "" || $eq == " ") return('ERRORE: Equazione non valida');
$eq = str_replace(' ', '', $eq);
// Controllo della sintassi
$terms = explode('=', $eq);
if($terms[0] == null || $terms[1] == null) return("ERRORE: Equazione non valida");
if (count($terms) != 2) {
return('ERRORE: Equazione non valida');
}
$eq = $terms[0] . '-(' . $terms[1] . ')';
if (substr_count($eq, '(') != substr_count($eq, ')')) {
return('ERRORE: Non tutte le parentesi sono state chiuse nell equazione [' . $eq . '].');
}
if (preg_match('/\([^)]*\(/', $eq)) {
return('Non ho idea di come risolvere questo! ['
. $eq . '].');
}
if (preg_match('/[^x0-9+*\/().=-]/', $eq)) {
return('ERRORE: Sono ammessi solo i caratteri x, 0-9, +, '
. '*, /, (, ), ., e - in [' . $eq . ']');
}
if (preg_match('/[^x0-9\)][-+\/*]/', $eq)) {
return('ERRORE: Puoi operare solo sui numeri in ['
. $eq . ']');
}
if (preg_match('/[-+\/*][^x0-9\(]/', $eq)) {
return('ERRORE: Puoi operare solo sui numeri in ['
. $eq . ']');
}
// Sostituisco x incognita con variabile php per renderla leggibile durante eval()
$eq = str_replace('x', '$x', $eq);
$y0 = $y1 = 0;
$x = 0; @eval('$y0 = ' . $eq . ';');
$x = 1; @eval('$y1 = ' . $eq . ';');
$slope = $y1 - $y0;
$intersect = $y0;
$soln = (-($intersect / $slope));
if($soln == 0) return("Impossibile!");
return (- ($intersect / $slope));
}
$eq = $_POST['eq'];
echo $eq, '
x = ', solve($eq), '
';
?>
Questo è il link alla pagina: http://www.ray97.com/tests/mah/solver.html
Provate con una qualsiasi operazione e aiutatemi a capire quei strani risultati!!