1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Tutorial Using equations in programming

Comments in 'Resources' started by SOFe, Aug 11, 2016.

  1. SOFe

    SOFe Banned

    May 28, 2016
    Minecraft User:
    Yes, equations don't exist in programming. Programming only has functions (~ formulas), no equations.

    An equation is handled by a human for solving. In the end, we don't want the equation. We only want to convert that equation into a formula for a subject.

    As the simplest example, to use the Pythagoras's theorem:
    c^2 = a^2 + b^2
    You have got c and a, and you want to find b.

    You don't try to write like this:
    $a ** $b ** $c ** 2;
    This is obviously syntax error, or if you are unlucky, unexpected behaviour is expected instead.

    You solve this equation by hand, making b the subject of the equation. Don't like pencil-and-paper calculation? Use Wolfram|Alpha.
    Wolfram|Alpha - solve a^2+b^2=c^2 for b

    We get:
    b = +- sqrt( c^2 - a^2)
    (Seriously, do we even need to use a pencil or a computer to find this obvious solution? :p)

    And obviously, we only want the positive solution. Therefore we can make such function:

    public function solveB($a$c){
    sqrt($c ** $a ** 2);
    The above is an introduction to using equations in programming.

    It can even grow more complex. For example, given a point, and we want to find its perpendicular distance from a line (defined by two points) (all three points indicated by position vectors):

    The above link to Wolfram MathWorld shows how to evaluate the answer using vectors, and gave us a beautiful formula:

    So, we can create this function with vectors: (the Vector3 in PocketMine actually reflects the concept of vectors in the mathematical world)

    public function pointLineDistance(Vector3 $pointVector3 $lineStartVector3 $lineEnd) : float{
    $point->subtract($lineStart)->cross($point->subtract($lineEnd))->length() / $lineEnd->subtract($lineStart)->length();
    Note that the Vector3::cross() function used here is the cross product function in vectors, which is really useful if you know how to use it.
    Legoboy0215 likes this.

Share This Page