Skip to content

solve and SolveEquations not solving correctly #682

@AcraeaTerpsicore

Description

@AcraeaTerpsicore
const nerdamer = require('nerdamer');
require('nerdamer/Algebra');
require('nerdamer/Calculus');
require('nerdamer/Solve');
const math=require('mathjs');

function trimBrackets(str) {
    return str.replace(/^\[|\]$/g, '');
}

// Function to evaluate and convert to complex numbers
const convertToComplex = (expressions) => {
    return expressions.map(expr => {
    try {
        // Evaluate the expression using math.js
        const result = math.evaluate(expr);
        return result; // Result will be a complex number if applicable
    } catch (error) {
        console.error(`Error evaluating expression: ${expr}`, error);
        return null; // Handle errors gracefully
    }
    });
};

const eqnString = 'z^4+1.4*z^3+0.71*z^2+0.154*z+0.012';

function test_solve(){
    console.log("===test_solve===")
    const solution = nerdamer.solve(eqnString, 'z');
    const roots = ( trimBrackets(solution.toString()) );
    console.log(roots);
    if (roots) {
        console.log( convertToComplex(roots.toString().split(",")) );
    } else {
        console.log(`\t No roots found or unable to solve equation.`);
    }
}

function test_solveEquations(){
    console.log("===test_solveEquations===");
    const solution1 =nerdamer.solveEquations(eqnString,'z');
    const solution1_string = solution1.toString();
    console.log(solution1_string);
    if (solution1) {
        console.log( convertToComplex(solution1_string.split(",")) );
    } else {
        console.log(`\t No roots found or unable to solve equation.`);
    }
}


test_solve();
test_solveEquations();

// npm init -y
// npm install nerdamer
// npm install mathjs
// node run test_nerdamer_solve.js
===test_solve===
-1/5,-2/5,(-138907099/400990255)*i-1/5,(-162503662/469107665)*i+1125899906842624/5629499534213125
[
  -0.2,
  -0.4,
  Complex { re: -0.2, im: -0.34641016151377546 },
  Complex { re: 0.19999999999999982, im: -0.3464101615137753 }
]
===test_solveEquations===
-1/5,-2/5,(-1/5)*i*sqrt(3)-1/5,(-2/5)*((1/2)*i*sqrt(3)+1/2)^2
[
  -0.2,
  -0.4,
  Complex { re: -0.2, im: -0.34641016151377546 },
  Complex { re: 0.1999999999999999, im: -0.34641016151377546 }
]

// However, in Mathematica
// Solve[z^4 + 1.4*z^3 + 0.71*z^2 + 0.154*z + 0.012 == 0, z]
// NSolve[z^4 + 1.4*z^3 + 0.71*z^2 + 0.154*z + 0.012, z]
// {{z -> -0.5}, {z -> -0.4}, {z -> -0.3}, {z -> -0.2}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions