【发布时间】:2020-02-12 21:22:41
【问题描述】:
我有一个包含 BigInt 类型的两列的数据框。然后我有一个用户定义的函数,它对这两列执行操作,最终结果应该是 Float 类型。
def generateNewColumnValue(firstColumnValue: BigInt, secondColumnValue: BigInt): Float = {
val calculated = scala.math.pow(firstColumnValue.toFloat / secondColumnValue, 1.0/3.0);
return calculated;
}
val generateNewColumnValueUDF = udf[Float, BigInt, BigInt](generateNewColumnValue);
如您所见,我在 UDF 的主体内部进行了一些非常简单的计算。问题是我收到以下错误,我不明白为什么不可能:
command-836521033094408:9: error: overloaded method value / with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Float <and>
(x: Int)Float <and>
(x: Char)Float <and>
(x: Short)Float <and>
(x: Byte)Float
cannot be applied to (BigInt)
val calculated = scala.math.pow(firstColumnValue.toFloat / secondColumnValue, 1.0/3.0);
问题是,如果我尝试将其转换为较低范围的类型(如 Int),我可能会在小数点后丢失一些值。
【问题讨论】:
-
new BigDecimal(firstColumnValue).divide(secondColumnValue, roundingMode).toFloat(如果可以的话,最好是 .toDouble) -
@Thilo BigInteger 不是 Scala 的一部分。我尝试使用 BigInt,但它不起作用。
-
对于 Scala
BigDecimal,你写BigDecimal(firstColumnValue),而不是new(除以/,而不是divide)。
标签: scala dataframe apache-spark-sql