Browse Source

Add frequency of

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

6
README.md

@ -118,6 +118,12 @@ arr.upper_fence(3) # => 47.5 (Q3 + 3 * IQR)
arr.upper_outliers(3) # => [1337]
```
### frequency_of
```crystal
[0, 1, 2, 3].frequency_of(0) # => 0.25 (amount of X among the population, divided by the size of the population)
```
## Development
- The lib is adapted to be usable with BigInt and BigFloat values

27
spec/math/frequency.cr

@ -0,0 +1,27 @@
FREQ_LIMIT = 100
describe Math::Frequency do
it "test trivia" 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
end
it "test basic" do
FREQ_LIMIT.times do |modi|
modulo = modi + 1
# we should have the same or more because we don't / modulo in the freq
arr = FREQ_LIMIT.times.to_a.map { |e| e % modulo }
(arr.frequency_of(0) >= (1.0f64 / modulo)).should be_true
next if modulo <= 20
# make an array with less or equal amount of iterations
arr_less = FREQ_LIMIT.times.to_a.map { |e| e % (modulo + 5) }
(arr.frequency_of(0) >= arr_less.frequency_of(0)).should be_true
# make an array with more or equal amount of iterations
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
end
end

10
src/lib/math/frequency.cr

@ -0,0 +1,10 @@
module Math::Frequency(T)
def frequency_of(value : T) : Float64
return 0.0f64 if empty?
count { |curr| curr == value }.to_f64 / size.to_f64
end
end
module Enumerable(T)
include Math::Frequency(T)
end
Loading…
Cancel
Save