Completed
Push — master ( 7edb5f...7211b3 )
by Patrick
02:04
created

VibratingString::getHarmonicSeries()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ExtendedStrings\Strings;
6
7
class VibratingString
8
{
9
    private $frequency;
10
11
    /**
12
     * @param float $frequency
13
     */
14
    public function __construct(float $frequency)
15
    {
16
        $this->frequency = $frequency;
17
    }
18
19
    /**
20
     * @param float $stringLength
21
     *
22
     * @return float
23
     */
24 View Code Duplication
    public function getStoppedFrequency(float $stringLength = 1.0): float
25
    {
26
        if (Math::isZero($stringLength)) {
27
            return 0;
28
        }
29
        $centsOverString = Cent::frequenciesToCents($stringLength, 1);
30
31
        return Cent::centsToFrequency($centsOverString, $this->frequency);
32
    }
33
34
    /**
35
     * @param float $stringLength
36
     *
37
     * @return float
38
     */
39
    public function getHarmonicSoundingFrequency(float $stringLength = 1.0): float
40
    {
41
        return Math::isZero($stringLength)
42
            ? 0
43
            : $this->frequency * self::getHarmonicNumber($stringLength);
44
    }
45
46
    /**
47
     * @param float $frequency
48
     *
49
     * @return float
50
     */
51 View Code Duplication
    public function getStringLength(float $frequency): float
52
    {
53
        if (Math::isZero($frequency)) {
54
            return 0;
55
        }
56
        $centsOverString = Cent::frequenciesToCents($this->frequency, $frequency);
57
58
        return $this->centsToStringLength($centsOverString);
59
    }
60
61
    /**
62
     * @param float $cents
63
     *   The number of cents between the open string and the stop.
64
     *
65
     * @return float
66
     *   The length of the remaining vibrating string.
67
     */
68
    private function centsToStringLength(float $cents): float
69
    {
70
        return 1 / pow(2, $cents / 1200);
71
    }
72
73
    /**
74
     * @param float $stringLength
75
     *
76
     * @throws \InvalidArgumentException
77
     *
78
     * @return int
79
     */
80
    public static function getHarmonicNumber(float $stringLength): int
81
    {
82
        $number = intval(1 / Math::gcd(1, $stringLength));
83
        if ($number > 100) {
84
            throw new \InvalidArgumentException(sprintf('Invalid string length for a harmonic: %f', $stringLength));
85
        }
86
87
        return $number;
88
    }
89
}
90