Update README.linux
[deliverable/titan.core.git] / compiler2 / Real.cc
CommitLineData
970ed795
EL
1///////////////////////////////////////////////////////////////////////////////
2// Copyright (c) 2000-2014 Ericsson Telecom AB
3// All rights reserved. This program and the accompanying materials
4// are made available under the terms of the Eclipse Public License v1.0
5// which accompanies this distribution, and is available at
6// http://www.eclipse.org/legal/epl-v10.html
7///////////////////////////////////////////////////////////////////////////////
8#include "Real.hh"
9#include "string.hh"
10#include "error.h"
11#include "Setting.hh"
12
13#include <stdio.h>
14#include <stdlib.h>
15#include <errno.h>
16#include <string.h>
17
18namespace Common {
19
20 bool isSpecialFloatValue(const Real& r)
21 {
22 return ((r!=r) || (r==REAL_INFINITY) || (r==-REAL_INFINITY));
23 }
24
25 string Real2string(const Real& r)
26 {
27 if (r == 0.0) return ((1.0/r)==-REAL_INFINITY) ? string("-0.0e0") : string("0.0e0");
28 else if (r == REAL_INFINITY) return string("INF");
29 else if (r == -REAL_INFINITY) return string("-INF");
30 else if (r != r) return string("NaN");
31
32 Real rabs = fabs(r);
33 int sign = (r / rabs < 0) ? -1 : 1;
34 double exponent = floor(log10(rabs));
35 double fraction = rabs * pow(10.0, -exponent);
36 double integral = floor(fraction);
37 char tmp[64];
38
39 sprintf(tmp, "%s%.15g%se%d",
40 (sign == -1) ? "-" : "",
41 fraction,
42 (fraction == integral) ? ".0" : "",
43 (int)exponent);
44
45 return string(tmp);
46 }
47
48 string Real2code(const Real& r)
49 {
50 if (r == 0.0) return ((1.0/r)==-REAL_INFINITY) ? string("-0.0") : string("0.0");
51 else if (r == REAL_INFINITY) return string("PLUS_INFINITY");
52 else if (r == -REAL_INFINITY) return string("MINUS_INFINITY");
53 else if (r != r) return string("NOT_A_NUMBER");
54 else {
55 Real rabs = fabs(r);
56 Real exponent = floor(log10(rabs));
57 Real mantissa = rabs * pow(10.0, -exponent);
58
59 char *tmp = mprintf("%s%.15g", r < 0.0 ? "-" : "", mantissa);
60 if (floor(mantissa) == mantissa) tmp = mputstr(tmp, ".0");
61 if (exponent != 0.0) tmp = mputprintf(tmp, "e%d", (int)exponent);
62 string ret_val(tmp);
63 Free(tmp);
64 return ret_val;
65 }
66 }
67
68 Real string2Real(const char *s, const Location& loc)
69 {
70 if (s[0] == '\0' || !strcmp(s, "0.0e0")) return 0.0;
71 else if (!strcmp(s, "-INF")) return -REAL_INFINITY;
72 else if (!strcmp(s, "INF")) return REAL_INFINITY;
73 else if (!strcmp(s, "NaN")) return REAL_NAN;
74 errno = 0;
75 Real r = strtod(s, NULL);
76 switch (errno) {
77 case ERANGE:
78 loc.error("Overflow when converting `%s' to a floating point value: %s",
79 s, strerror(errno));
80 break;
81 case 0:
82 break;
83 default:
84 FATAL_ERROR("string2Real(): Unexpected error when converting `%s' to real: %s",
85 s, strerror(errno));
86 }
87 return r;
88 }
89
90} // namespace Common
This page took 0.026529 seconds and 5 git commands to generate.