Implements Banker's rounding: numbers that are equidistant between two integers are rounded towards even.
| 1091 | // Implements Banker's rounding: numbers that are equidistant between two |
| 1092 | // integers are rounded towards even. |
| 1093 | XlaOp RoundToEven(XlaOp x) { |
| 1094 | auto& b = *x.builder(); |
| 1095 | return b.ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { |
| 1096 | // Reject non-real non-fp inputs (What does it even mean to round a complex |
| 1097 | // number? Do you round each component equally? In that case, you should |
| 1098 | // just ask for that explicitly.) |
| 1099 | TF_RETURN_IF_ERROR(EnsureOperandIsRealFp("RoundToEven", x)); |
| 1100 | |
| 1101 | auto half = ScalarLike(x, 0.5); |
| 1102 | auto one = ScalarLike(x, 1.0); |
| 1103 | auto two = ScalarLike(x, 2.0); |
| 1104 | |
| 1105 | auto round_val = Floor(x); |
| 1106 | auto fraction = x - round_val; |
| 1107 | auto nearest_even_int = round_val - two * Floor(half * x); |
| 1108 | auto is_odd = Eq(nearest_even_int, one); |
| 1109 | return Select(Or(Gt(fraction, half), And(Eq(fraction, half), is_odd)), |
| 1110 | round_val + one, round_val); |
| 1111 | }); |
| 1112 | } |
| 1113 | |
| 1114 | // Trigonometric functions. |
| 1115 |