Browse Source

Add all_frequencies

master
Arthur POULET 3 years ago
parent
commit
e82eac24e1
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 3
      README.md
  2. 7
      spec/math/frequency.cr
  3. 8
      src/lib/math/frequency.cr

3
README.md

@ -118,10 +118,11 @@ arr.upper_fence(3) # => 47.5 (Q3 + 3 * IQR)
arr.upper_outliers(3) # => [1337]
```
### frequency_of
### Frequency
```crystal
[0, 1, 2, 3].frequency_of(0) # => 0.25 (amount of X among the population, divided by the size of the population)
[0, 0, 1, 2, 3].all_frequencies # => { 0 => 0.4, 1 => 0.2, 2 => 0.2, 3 => 0.2}
```
## Development

7
spec/math/frequency.cr

@ -5,6 +5,11 @@ describe Math::Frequency do
([]of Int32).frequency_of(0).should eq 0.0
[0, 1, 2, 3].frequency_of(0).should eq 0.25
[0, 0, 1, 2, 3].frequency_of(0).should eq 0.40
[0, 0, 1, 2, 3].all_frequencies.should eq({ 0 => 0.4, 1 => 0.2, 2 => 0.2, 3 => 0.2 })
# allfreq1 = [0, 0, 1, 2, 3].all_frequencies(2)
# allfreq1[1].should eq 0.4
# allfreq1.size.should eq 2
# expect_raises(Error) { [0, 0, 1, 2, 3].all_frequencies(2, true) }
end
it "test basic" do
@ -23,5 +28,7 @@ describe Math::Frequency do
arr_more = FREQ_LIMIT.times.to_a.map { |e| e % (modulo - 5) }
(arr.frequency_of(0) <= arr_more.frequency_of(0)).should be_true
end
[0, 0, 0, 0, 1, 1, 1, 2, 2, 3].all_frequencies.should eq({ 0 => 0.4, 1 => 0.3, 2 => 0.2, 3 => 0.1 })
end
end

8
src/lib/math/frequency.cr

@ -3,6 +3,14 @@ module Math::Frequency(T)
return 0.0f64 if empty?
count { |curr| curr == value }.to_f64 / size.to_f64
end
def all_frequencies : Hash(T, Float64)
values = to_set
frequencies = Hash(T, Float64).new(0.0f64, values.size)
each { |value| frequencies[value] += 1 }
frequencies.each { |k, _| frequencies[k] = frequencies[k] / size }
frequencies
end
end
module Enumerable(T)

Loading…
Cancel
Save