In the previous article "PHP Algorithm Exercise 9: Convert all even numbers to all odd numbers" I introduced to you how to convert all even numbers to all odd numbers through PHP, so today I will continue to show you Bringing the PHP algorithm exercise series~
This article will introduce to you how to calculate the radius and center coordinates of a circle through PHP~
The specific problem description is "How to write a PHP program to calculate the radius and center coordinates (x, y) of a circle formed by three given points on a plane”?
This problem is equivalent to a mathematical problem. Given three points, determine the radius and center coordinates of a circle.
Look at the picture below:
I will provide you with several formulas:
The formula for setting up a circle is as follows:
Convert the circle equation into a standard equation:
Substitute the above coefficients to solve the circle center (x, y) and radius R:
PHP implementation code is as follows:
<?php $x1 = 0; $y1 = 0; $x2 = 2; $y2 = 0; $x3 = 2; $y3 = 2; $a1 = 2 * ($x2 - $x1); $b1 = 2 * ($y2 - $y1); $c1 = $x1 * $x1 - $x2 * $x2 + $y1 *$y1 - $y2 * $y2; $a2 = 2 * ($x3 - $x1); $b2 = 2 * ($y3 - $y1); $c2 = $x1 * $x1 - $x3 * $x3 + $y1 *$y1 - $y3 * $y3; $x = ($b1 * $c2 - $b2 * $c1) / ($a1 * $b2 - $a2 * $b1); $y = ($c1 * $a2 - $c2 * $a1) / ($a1 * $b2 - $a2 * $b1); $r = sqrt(($x - $x1) * ($x - $x1) + ($y - $y1) * ($y - $y1)); printf("圆的中心坐标(x,y)和半径:<br>"); printf("(%.3f %.3f) %.3f\n", $x, $y, $r);
The calculation result is:
圆的中心坐标(x,y)和半径: (1.000 1.000) 1.414
Note:
sqrt() function Returns the square root of a number.
The syntax is "sqrt(x)
", which means returning the square root of x.
The parameter x represents a number. If the parameter x is a negative number, the sqrt() function returns -1.#IND. (Attachment: Before PHP 5.3.0, this function treated the array as a string Array, thus returning a string with a length of 5 and generating an E_NOTICE level error.)
Finally, I recommend the latest to everyone The most comprehensive "PHP Video Tutorial" ~ Come and learn!
The above is the detailed content of PHP algorithm exercise ten: Calculate the radius and center coordinates of a circle. For more information, please follow other related articles on the PHP Chinese website!