Skip to content

Implement the fmod function #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 23, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ object FunctionRegistry {
expression[Pow]("pow"),
expression[Pow]("power"),
expression[Pmod]("pmod"),
expression[Fmod]("fmod"),
expression[UnaryPositive]("positive"),
expression[Rint]("rint"),
expression[Round]("round"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,3 +514,47 @@ case class Pmod(left: Expression, right: Expression) extends BinaryArithmetic {
if (r.compare(Decimal.ZERO) < 0) {(r + n) % n} else r
}
}

case class Fmod(left: Expression, right: Expression)
extends BinaryExpression with Serializable with ImplicitCastInputTypes {

override def inputTypes: Seq[DataType] = Seq(DoubleType, DoubleType)

override def toString: String = s"fmod($left, $right)"

override def dataType: DataType = DoubleType

override def eval(input: InternalRow): Any = {
val input2 = right.eval(input)
if (input2 == null || input2 == 0) {
null
} else {
val input1 = left.eval(input)
if (input1 == null) {
null
} else {
input1.asInstanceOf[Double] % input2.asInstanceOf[Double]
}
}
}

override def genCode(ctx: CodeGenContext, ev: GeneratedExpressionCode): String = {
val eval1 = left.gen(ctx)
val eval2 = right.gen(ctx)
s"""
${eval2.code}
boolean ${ev.isNull} = ${eval2.isNull} || ${eval2.value} == 0;

${ctx.javaType(dataType)} ${ev.value} = ${ctx.defaultValue(dataType)};
if (!${ev.isNull}) {
${eval1.code}
if (!${eval1.isNull}) {
${ev.value} = ${eval1.value} % ${eval2.value};
} else {
${ev.isNull} = true;
}
}
"""
}

}
9 changes: 9 additions & 0 deletions sql/core/src/main/scala/org/apache/spark/sql/functions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1816,6 +1816,15 @@ object functions extends LegacyFunctions {
*/
def toRadians(columnName: String): Column = toRadians(Column(columnName))

/**
* Computes a floating-point remaineder value. The result has the same sign as the denominator.
*
* @group math_funcs
*/
def fmod(numerator: Column, denominator: Column): Column = withExpr {
Fmod(numerator.expr, denominator.expr)
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Misc functions
//////////////////////////////////////////////////////////////////////////////////////////////
Expand Down