通用数字分割 [英] Generic Numeric division

查看:115
本文介绍了通用数字分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我们可以取任何数字类型的任何值,并将其除以任何数字类型的任何非零值,并获得合理结果。

  212.7 / 6 // Double = 35.449999999999996 
77L / 2.1F // Float = 36.666668

我发现的一个例外是,我们不能将 BigInt 与小数类型( Float Double )。 在泛型领域,但是, Integral 小数类型之间有一个有趣的区别。


$ b $ (a:I,b:I)(imp ev:Integral [I])= ev.quot( a,b)

//或这个
def divideF [F](a:F,b:F)(隐式ev:小数[F])= ev.div(a, b)

//但不是这
def divideN [N](a:N,b:N)(imp ev:Numeric [N])= ev.???((a ,b)

虽然我很好奇这是为什么,回覆al问题是:是否有某种解决方法可用于避开此限制?

解决方案

原因是因为整数除法和浮点除法是两个 不同的操作,所以所有的 Numerics 不共享一个共同的除法操作,尽管人们可能认为它们都是分割。



解决方法是创建4个除法运算:积分/积分,积分/分数,分数/积分,分数/分数。以您认为合适的特定应用程序进行计算。当我为我写的一个计算器做了这个工作时,如果可能的话,我把它保存在Integral中,否则就投到Double。


As a general rule, we can take any value of any number type, and divide it by any non-zero value of any number type, and get a reasonable result.

212.7 / 6   // Double = 35.449999999999996
77L / 2.1F  // Float = 36.666668

The one exception, that I've found, is that we can't mix a BigInt with a fractional type (Float or Double).

In the realm of generics, however, there's this interesting distinction between Integral and Fractional types.

// can do this
def divideI[I](a: I, b: I)(implicit ev: Integral[I])   = ev.quot(a,b)

// or this
def divideF[F](a: F, b: F)(implicit ev: Fractional[F]) = ev.div(a,b)

// but not this
def divideN[N](a: N, b: N)(implicit ev: Numeric[N])    = ev.???(a,b)

While I am curious as to why this is, the real question is: Is there some kind of workaround available to sidestep this limitation?

解决方案

The reason is because integer division and float division are two very different operations, so all Numerics do not share a common division operation, although humans might think of them both as "division."

The workaround would be to create 4 division operations: Integral/Integral, Integral/Fractional, Fractional/Integral, Fractional/Fractional. Do the calculation in whatever application-specific way you feel is appropriate. When I did this for a calculator I wrote, I kept it in Integral if possible, and cast to Double otherwise.

这篇关于通用数字分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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