slightlyoff / cassowary.js

Cassowary/JS, better, faster, future-ready
Other
1.69k stars 107 forks source link

Expression with x^2 #74

Closed raineorshine closed 8 years ago

raineorshine commented 8 years ago

Why can't cassowary solve equations with squares? I'm guessing it has something to do with it being a nonlinear function...? I am a beginner to constraint solvers.

var c = require('cassowary');

var solver = new c.SimplexSolver();
var x = new c.Variable();
var squared = c.times(x, x);
var constraint = new c.Equation(squared, 25);
solver.add(constraint);
console.log(x.value);

Results in:

(c.NonExpression) The resulting expression would be non
davesann commented 8 years ago

Cassowary is based on the Simplex Algorithm for solving linear programming/optimisation problems. As you noted multiplying (or dividing) variables makes the problem non linear.

You can get an intuitive understanding for why this is the case here (and lots of other sources):
http://explain-that.blogspot.com.au/2011/06/logic-of-how-simplex-method-works.html

The key thing to see in the linked page is that linearity makes the solution space a convex closed shape with linear sides and that the optimal solution to the problem must be one of the corner points of this shape.

It is not that non-linear problems cannot be solved (to some degree) - but that linearity is a precondition that the simplex algorithm uses in order to be able to make certain optimisations and ignore many possible solutions. This makes it relatively fast.

You can't do this if you use non-linear equations and so the algorithms require more computation to reach a solution.

raineorshine commented 8 years ago

Thank you