xref: /aosp_15_r20/external/tensorflow/tensorflow/lite/kernels/internal/reference/round.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_ROUND_H_
16 #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_ROUND_H_
17 
18 #include <cmath>
19 
20 #include "tensorflow/lite/kernels/internal/types.h"
21 
22 namespace tflite {
23 
24 namespace reference_ops {
25 
RoundToNearest(float value)26 inline float RoundToNearest(float value) {
27   auto floor_val = std::floor(value);
28   auto diff = value - floor_val;
29   if ((diff < 0.5f) ||
30       ((diff == 0.5f) && (static_cast<int>(floor_val) % 2 == 0))) {
31     return floor_val;
32   } else {
33     return floor_val = floor_val + 1.0f;
34   }
35 }
36 
Round(const RuntimeShape & input_shape,const float * input_data,const RuntimeShape & output_shape,float * output_data)37 inline void Round(const RuntimeShape& input_shape, const float* input_data,
38                   const RuntimeShape& output_shape, float* output_data) {
39   const int flat_size = MatchingFlatSize(input_shape, output_shape);
40   for (int i = 0; i < flat_size; ++i) {
41     // Note that this implementation matches that of tensorFlow tf.round
42     // and corresponds to the bankers rounding method.
43     // cfenv (for fesetround) is not yet supported universally on Android, so
44     // using a work around.
45     output_data[i] = RoundToNearest(input_data[i]);
46   }
47 }
48 
49 }  // namespace reference_ops
50 }  // namespace tflite
51 #endif  // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_ROUND_H_
52