- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class InterpolationLabsCommand extends ContainerAwareCommand
{
/**
* nodes for interpolation polynomial
*/
protected $_nodes;
protected function configure()
{
$this
->setName('app:interpolation:labs')
->setDescription('interpolation')
->addOption('nodes-count', null, InputOption::VALUE_REQUIRED,
'Sets the number of nodes for interpolation.', null);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$intervalStart = -3;
$intervalEnd = 3;
$nodesCount = $input->getOption('nodes-count');
$this->generateSeries($nodesCount, $intervalStart, $intervalEnd, function($x) {
return sin($x);
});
foreach (range($intervalStart, $intervalEnd, 0.1) as $value) {
$result = $this->getLagrangeValue($value);
$output->writeln("$value $result");
}
}
/**
* Find value for lagrange interpolation polynomial at n nodes
* @throw \Exception
*
* @return
*/
protected function getLagrangeValue($x)
{
$w = function($nodeKey) use ($x) {
if (!array_key_exists($nodeKey, $this->_nodes)) {
throw new \Exception("The key is not exists to the array nodes");
}
$return = 1;
foreach ($this->_nodes as $key => $node) {
if ($key == $nodeKey) {
continue;
}
$return *= ($x - $node->x)/($this->getNode($nodeKey)->x - $node->x);
}
return $return;
};
$result = 0;
foreach ($this->_nodes as $nodeKey => $node) {
$a = $w($nodeKey);
$result += $w($nodeKey) * $node->fx;
}
return $result;
}
protected function getNode($i)
{
return $this->_nodes[$i];
}
private function generateSeries($num, $intervalStart, $intervalEnd, $fun)
{
for ($i=0; $i < $num; $i++) {
$x = $intervalStart + ($intervalEnd - $intervalStart)/($num-1) * $i;
$this->_nodes[] = (object) array('x' => $x,
'fx' => $fun($x));
}
}
}