Completed
Push — work-fleets ( ec9dc8...d7065d )
by SuperNova.WS
06:07
created

snMath   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 185
Duplicated Lines 8.65 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 16
loc 185
rs 8.6
ccs 0
cts 92
cp 0
wmc 37
lcom 0
cbo 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A sn_rand_gauss() 0 15 4
B sn_rand_gauss_range() 0 13 7
A average() 0 3 3
B median() 0 35 5
F linear_calc() 16 44 14
A geometry_progression_sum() 0 3 2
A sn_floor() 0 3 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Created by Gorlum 13.08.2016 15:18
4
 */
5
6
namespace Common;
7
8
9
class snMath {
10
11
  /**
12
   * Эта функция выдает нормально распределенное случайное число с матожиднием $mu и стандартным отклонением $sigma
13
   *
14
   * $strict - количество $sigma, по которым идет округление функции. Т.е. $strict = 3 означает, что диапазон значений обрезается по +-3 * $sigma
15
   * Используется http://ru.wikipedia.org/wiki/Преобразование_Бокса_—_Мюллера
16
   *
17
   * @param int  $mu
18
   * @param int  $sigma
19
   * @param bool $strict
20
   *
21
   * @return int
22
   */
23
  public static function sn_rand_gauss($mu = 0, $sigma = 1, $strict = false) {
24
    // http://ru.wikipedia.org/wiki/Среднеквадратическое_отклонение
25
    // При $mu = 0 (график симметричный, цифры только для половины графика)
26
    // От 0 до $sigma ~ 34.1%
27
    // От $sigma до 2 * $sigma ~ 13.6%
28
    // От 2 * $sigma до 3 * $sigma ~ 2.1%
29
    // От 3 * $sigma до бесконечности ~ 0.15%
30
    // Не менее 99.7% случайных величин лежит в пределах +-3 $sigma
31
32
    $max_rand = mt_getrandmax();
33
    $random = cos(2 * pi() * (mt_rand(1, $max_rand) / $max_rand)) * sqrt(-2 * log(mt_rand(1, $max_rand) / $max_rand));
34
    $random = $strict === false ? $random : ($random > $strict ? $strict : ($random < -$strict ? -$strict : $random));
35
36
    return $mu + $sigma * $random;
37
  }
38
39
40
  /**
41
   * Функция возвращает случайное нормально распределенное целое число из указанного промежутка
42
   *
43
   * @param float      $range_start - Начало диапазона
44
   * @param float      $range_end - Конец диапазона
45
   * @param bool|int   $round - До скольки знаков округлять результат. False - не округлять, True - округлять до целого, 1 - округлять до десятков, 2 - до сотен итд
46
   * @param int        $strict - В сколько сигм надо уложить результат
47
   * @param bool|false $cut_extreme - надо ли обрезать крайние значения. Например, при $strict = 2 их слишком много
48
   *
49
   * @return float|int
50
   */
51
  public static function sn_rand_gauss_range($range_start, $range_end, $round = true, $strict = 4, $cut_extreme = false) {
52
    if ($cut_extreme) {
53
      $range_start--;
54
      $range_end++;
55
    }
56
    do {
57
      $random = static::sn_rand_gauss(($range_start + $range_end) / 2, ($range_end - $range_start) / $strict / 2, $strict);
0 ignored issues
show
Documentation introduced by
$strict is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
58
      $round_emul = pow(10, $round === true ? 0 : $round);
59
      $result = $round ? round($random * $round_emul) / $round_emul : $random;
60
    } while ($cut_extreme && ($result == $range_start || $result == $range_end));
61
62
    return $result;
63
  }
64
65
  /**
66
   * Returns average of array
67
   *
68
   * @param array $arr
69
   *
70
   * @return float
71
   */
72
  public static function average($arr) {
73
    return is_array($arr) && count($arr) ? array_sum($arr) / count($arr) : 0;
74
  }
75
76
  /**
77
   * Return median of values - list of them or array of values
78
   *
79
   * @return bool|float|mixed
80
   */
81
  public static function median() {
82
    $args = func_get_args();
83
84
    switch (func_num_args()) {
85
      case 0:
86
        // trigger_error('median() requires at least one parameter',E_USER_WARNING);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
87
        return false;
88
      break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
89
90
      case 1:
91
        $args = array_pop($args);
92
      // fallthrough
93
94
      default:
95
        if (!is_array($args)) {
96
          // trigger_error('median() requires a list of numbers to operate on or an array of numbers', E_USER_NOTICE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
97
          return false;
98
        }
99
100
        sort($args);
101
102
        $n = count($args);
103
        $h = intval($n / 2);
104
105
        if ($n % 2 == 0) {
106
          $median = ($args[$h] + $args[$h - 1]) / 2;
107
        } else {
108
          $median = $args[$h];
109
        }
110
111
      break;
112
    }
113
114
    return $median;
115
  }
116
117
  /**
118
   * Basic linear equation system solver
119
   *
120
   * @param array $linear
121
   * @param int   $from
122
   * @param bool  $logProcess
123
   */
124
  public static function linear_calc(&$linear, $from = 0, $logProcess = false) {
125 View Code Duplication
    for ($i = $from; $i < count($linear); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
      $eq = &$linear[$i];
127
      for ($j = count($eq) - 1; $j >= $from; $j--) {
128
        $eq[$j] /= $eq[$from];
129
      }
130
    }
131
    if ($logProcess) {
132
      pdump($linear, 'Нормализовано по х' . $from);
133
    }
134
135 View Code Duplication
    for ($i = $from + 1; $i < count($linear); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136
      $eq = &$linear[$i];
137
      for ($j = count($eq) - 1; $j >= $from; $j--) {
138
        $eq[$j] -= $linear[$from][$j];
139
      }
140
    }
141
    if ($logProcess) {
142
      pdump($linear, 'Подставили х' . $from);
143
    }
144
145
    if ($from < count($linear) - 1) {
146
      static::linear_calc($linear, $from + 1, $logProcess);
147
    }
148
149
    if ($from) {
150
      for ($i = 0; $i < $from; $i++) {
151
        $eq = &$linear[$i];
152
        for ($j = count($eq) - 1; $j >= $from; $j--) {
153
          $eq[$j] = $eq[$j] - $eq[$from] * $linear[$from][$j];
154
        }
155
      }
156
      if ($logProcess) {
157
        pdump($linear, 'Подставили обратно х' . $from);
158
      }
159
    } else {
160
      if ($logProcess) {
161
        pdump($linear, 'Результат' . $from);
162
      }
163
      foreach ($linear as $index => &$eq) {
164
        pdump($eq[count($linear)], 'x' . $index);
165
      }
166
    }
167
  }
168
169
  /**
170
   * Calculates geometric progression sum for N-th element
171
   *
172
   * @param int   $n
173
   * @param float $b1
174
   * @param float $q
175
   *
176
   * @return float
177
   */
178
  public static function geometry_progression_sum($n, $b1, $q) {
179
    return $q != 1 ? ($b1 * (pow($q, $n) - 1) / ($q - 1)) : ($n * $b1);
180
  }
181
182
  /**
183
   * Floor to less preferable value
184
   *
185
   * @param float $value
186
   *
187
   * @return float
188
   */
189
  public static function sn_floor($value) {
190
    return $value >= 0 ? floor($value) : ceil($value);
191
  }
192
193
}
194