百分位计算器 [英] Percentile calculator

查看:65
本文介绍了百分位计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个小方法来从 seq 计算给定的百分位数.它有效......几乎.问题是我不知道为什么不起作用.我希望你的一个比我更聪明"的人能帮我解决这个问题.

I have been trying to create a small method to calculate given percentile from a seq. It works.. almost. Problem is I don't know why is doesn't work. I was hoping one of your 'a bit smarter' people than me could help me with it.

我希望结果是它会从 seq 返回项目,即 seq 的 n prosent 小于等于返回值.

What I hope the result would be is that it would return the item from the seq that n prosent of the seq is smaller than equal than returned value.

def percentile[Int](p: Int)(seq: Seq[Int]) = {
  require(0 <= p && p <= 100)                      // some value requirements
  require(!seq.isEmpty)                            // more value requirements
  val sorted = seq.sorted
  val k = math.ceil((seq.length - 1) * (p / 100)).toInt
  return sorted(k)
}

例如,如果我有

val v = Vector(7, 34, 39, 18, 16, 17, 21, 36, 17, 2, 4, 39, 4, 19, 2, 12, 35, 13, 40, 37)

并且我调用我的函数 percentile(11)(v) 返回值是 2.但是,向量的 10% 小于或等于 2,而不是我调用的 11%.percentile(11)(v) 应该返回 4.

and I call my function percentile(11)(v) return value is 2. However, 10% of the vector are smaller or equal than 2, not 11% like I am calling. percentile(11)(v) should return 4.

推荐答案

你的错误在这一行:

 val k = math.ceil((seq.length - 1) * (p / 100)).toInt

特别是这里:p/100.作为 p 一个 Int <= 100 且 >= 0,p/100 将始终等于 0 或 1(如果 p == 100>).如果你想要一个浮点结果,你必须将两个值之一扩大到两倍:p/100.0

and particularly here: p / 100. Being p an Int <= 100 and >= 0, p/100 will always be equal to 0 or 1 (if p == 100). If you want a floating point result, you have to widen one of the two values to double: p/100.0

 val k = math.ceil((seq.length - 1) * (p / 100.0)).toInt

附带说明:您不需要 [Int] 类型参数

On a side note: you don't need the [Int] type parameter

这篇关于百分位计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆