Advertisement
  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
    Offline

    SOFe Banned

    Joined:
    May 28, 2016
    Posts:
    386
    Minecraft User:
    Herobrine
    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:
    Code:
    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:
    PHP:
    $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:
    Code:
    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:

    PHP:
    public function solveB($a$c){
      return 
    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):
    http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html

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

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

    PHP:
    public function pointLineDistance(Vector3 $pointVector3 $lineStartVector3 $lineEnd) : float{
      return 
    $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

Advertisement