Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Created March 3, 2025 12:30
Show Gist options
  • Save pedrobertao/b608acef650661fd33f5d89edf79c252 to your computer and use it in GitHub Desktop.
Save pedrobertao/b608acef650661fd33f5d89edf79c252 to your computer and use it in GitHub Desktop.
IQR Method Claude.ai in Go
package main
import (
"fmt"
"math"
"sort"
)
// RemoveOutliers removes outliers from a slice of prices using the IQR method
// multiplier is typically 1.5 for mild outlier detection or 3 for extreme outliers
func RemoveOutliers(prices []float64, multiplier float64) []float64 {
if len(prices) <= 3 {
return prices // Not enough data to determine outliers
}
// Create a copy of the prices to avoid modifying the original
sortedPrices := make([]float64, len(prices))
copy(sortedPrices, prices)
// Sort the array
sort.Float64s(sortedPrices)
// Calculate quartile positions
q1Pos := int(math.Floor(float64(len(sortedPrices)) * 0.25))
q3Pos := int(math.Floor(float64(len(sortedPrices)) * 0.75))
// Get quartile values
q1 := sortedPrices[q1Pos]
q3 := sortedPrices[q3Pos]
// Calculate IQR (Interquartile Range)
iqr := q3 - q1
// Define bounds for outliers
lowerBound := q1 - (multiplier * iqr)
upperBound := q3 + (multiplier * iqr)
// Filter out the outliers
result := []float64{}
for _, price := range prices {
if price >= lowerBound && price <= upperBound {
result = append(result, price)
}
}
return result
}
// Usage example
func main() {
prices := []float64{10.5, 11.2, 12.0, 12.3, 12.5, 12.7, 13.0, 13.5, 50.0, 100.0, 2.0}
filteredPrices := RemoveOutliers(prices, 1.5)
fmt.Println("Unfiltered", prices)
// 10.5 11.2 12 12.3 12.5 12.7 13 13.5 50 100 2]
// filteredPrices now contains the prices with outliers removed
fmt.Println("Filtered", filteredPrices)
// [10.5 11.2 12 12.3 12.5 12.7 13 13.5]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment