math.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package dara
  2. import (
  3. "math"
  4. "math/rand"
  5. "reflect"
  6. "time"
  7. )
  8. // Number is an interface that can be implemented by any numeric type
  9. type Number interface{}
  10. // toFloat64 converts a numeric value to float64 for comparison
  11. func toFloat64(n Number) float64 {
  12. v := reflect.ValueOf(n)
  13. switch v.Kind() {
  14. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  15. return float64(v.Int())
  16. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  17. return float64(v.Uint())
  18. case reflect.Float32, reflect.Float64:
  19. return v.Float()
  20. default:
  21. panic("unsupported type")
  22. }
  23. }
  24. // Floor returns the largest integer less than or equal to the input number as int
  25. func Floor(n Number) int {
  26. v := toFloat64(n)
  27. floorValue := math.Floor(v)
  28. return int(floorValue)
  29. }
  30. // Round returns the nearest integer to the input number as int
  31. func Round(n Number) int {
  32. v := toFloat64(n)
  33. roundValue := math.Round(v)
  34. return int(roundValue)
  35. }
  36. func Random() float64 {
  37. rand.Seed(time.Now().UnixNano())
  38. return rand.Float64()
  39. }