aa - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of aa.php

  1. <?php
  2.  
  3. // Function representing the equation: x^3 + 2x - (sin(x) + 1)
  4. function equation($x) {
  5.     return pow($x, 3) + 2 * $x - (sin($x) + 1);
  6. }
  7.  
  8. // Secant method function to approximate the root of the equation
  9. function secantMethod($x0, $x1, $accuracy) {
  10.     $maxIterations = 1000;
  11.  
  12.     // Iterative loop for the Secant method
  13.     for ($i = 0; $i < $maxIterations; ++$i) {
  14.         // Calculate function values at current points
  15.         $fX0 = equation($x0);
  16.         $fX1 = equation($x1);
  17.  
  18.         // Compute the next approximation using the Secant method formula
  19.         $x2 = $x1 - ($fX1 * ($x1 - $x0)) / ($fX1 - $fX0);
  20.  
  21.         // Check if the desired accuracy is achieved
  22.         if (abs($x2 - $x1) < $accuracy) {
  23.             return $x2;
  24.         }
  25.  
  26.         // Update points for the next iteration
  27.         $x0 = $x1;
  28.         $x1 = $x2;
  29.     }
  30.  
  31.     // If the method does not converge within the specified iterations
  32.     return null;
  33. }
  34.  
  35. // Case (i) X0 = 0.5, X1 = 0.6
  36. $x0_case1 = 0.5;
  37. $x1_case1 = 0.6;
  38. $root_case1 = secantMethod($x0_case1, $x1_case1, 1e-15);
  39.  
  40. echo "Root for case (i): " . number_format($root_case1, 15) . "\n";
  41.  
  42. // Case (ii) X0 = 0, X1 = 1
  43. $x0_case2 = 0;
  44. $x1_case2 = 1;
  45. $root_case2 = secantMethod($x0_case2, $x1_case2, 1e-15);
  46.  
  47. echo "Root for case (ii): " . number_format($root_case2, 15) . "\n";
  48.  
  49. ?>
File Description
  • aa
  • PHP Code
  • 07 Feb-2024
  • 1.33 Kb
You can Share it: