generic_float.odin 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package strconv
  2. import "decimal"
  3. Decimal_Slice :: struct {
  4. digits: []byte,
  5. count: int,
  6. decimal_point: int,
  7. neg: bool,
  8. }
  9. Float_Info :: struct {
  10. mantbits: uint,
  11. expbits: uint,
  12. bias: int,
  13. }
  14. _f16_info := Float_Info{10, 5, -15}
  15. _f32_info := Float_Info{23, 8, -127}
  16. _f64_info := Float_Info{52, 11, -1023}
  17. /*
  18. Converts a floating-point number to a string with the specified format and precision.
  19. **Inputs**
  20. buf: A byte slice to store the resulting string
  21. val: The floating-point value to be converted
  22. fmt: The formatting byte, accepted values are 'e', 'E', 'f', 'F', 'g', 'G'
  23. precision: The number of decimal places to round to
  24. bit_size: The size of the floating-point number in bits, valid values are 16, 32, 64
  25. Example:
  26. buf: [32]byte
  27. val := 3.141592
  28. fmt := 'f'
  29. precision := 2
  30. bit_size := 64
  31. result := strconv.generic_ftoa(buf[:], val, fmt, precision, bit_size) -> "3.14"
  32. **Returns**
  33. - A byte slice containing the formatted string
  34. */
  35. generic_ftoa :: proc(buf: []byte, val: f64, fmt: byte, precision, bit_size: int) -> []byte {
  36. bits: u64
  37. flt: ^Float_Info
  38. switch bit_size {
  39. case 16:
  40. bits = u64(transmute(u16)f16(val))
  41. flt = &_f16_info
  42. case 32:
  43. bits = u64(transmute(u32)f32(val))
  44. flt = &_f32_info
  45. case 64:
  46. bits = transmute(u64)val
  47. flt = &_f64_info
  48. case:
  49. panic("strconv: invalid bit_size")
  50. }
  51. neg := bits>>(flt.expbits+flt.mantbits) != 0
  52. exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1)
  53. mant := bits & (u64(1) << flt.mantbits - 1)
  54. switch exp {
  55. case 1<<flt.expbits - 1:
  56. s: string
  57. if mant != 0 {
  58. s = "NaN"
  59. } else if neg {
  60. s = "-Inf"
  61. } else {
  62. s = "+Inf"
  63. }
  64. n := copy(buf, s)
  65. return buf[:n]
  66. case 0: // denormalized
  67. exp += 1
  68. case:
  69. mant |= u64(1) << flt.mantbits
  70. }
  71. exp += flt.bias
  72. d_: decimal.Decimal
  73. d := &d_
  74. decimal.assign(d, mant)
  75. decimal.shift(d, exp - int(flt.mantbits))
  76. digs: Decimal_Slice
  77. prec := precision
  78. shortest := prec < 0
  79. if shortest {
  80. round_shortest(d, mant, exp, flt)
  81. digs = Decimal_Slice{digits = d.digits[:], count = d.count, decimal_point = d.decimal_point}
  82. switch fmt {
  83. case 'e', 'E': prec = digs.count-1
  84. case 'f', 'F': prec = max(digs.count-digs.decimal_point, 0)
  85. case 'g', 'G': prec = digs.count
  86. }
  87. } else {
  88. switch fmt {
  89. case 'e', 'E': decimal.round(d, prec+1)
  90. case 'f', 'F': decimal.round(d, d.decimal_point+prec)
  91. case 'g', 'G':
  92. if prec == 0 {
  93. prec = 1
  94. }
  95. decimal.round(d, prec)
  96. }
  97. digs = Decimal_Slice{digits = d.digits[:], count = d.count, decimal_point = d.decimal_point}
  98. }
  99. return format_digits(buf, shortest, neg, digs, prec, fmt)
  100. }
  101. /*
  102. Converts a decimal floating-point number into a byte buffer with the given format
  103. **Inputs**
  104. - buf: The byte buffer to store the formatted number
  105. - shortest: If true, generates the shortest representation of the number
  106. - neg: If true, the number is negative
  107. - digs: The decimal number to be formatted
  108. - precision: The number of digits after the decimal point
  109. - fmt: The format specifier (accepted values: 'f', 'F', 'e', 'E', 'g', 'G')
  110. **Returns**
  111. - A byte slice containing the formatted decimal floating-point number
  112. */
  113. format_digits :: proc(buf: []byte, shortest: bool, neg: bool, digs: Decimal_Slice, precision: int, fmt: byte) -> []byte {
  114. Buffer :: struct {
  115. b: []byte,
  116. n: int,
  117. }
  118. to_bytes :: proc(b: Buffer) -> []byte {
  119. return b.b[:b.n]
  120. }
  121. add_bytes :: proc(buf: ^Buffer, bytes: ..byte) {
  122. buf.n += copy(buf.b[buf.n:], bytes)
  123. }
  124. b := Buffer{b = buf}
  125. prec := precision
  126. switch fmt {
  127. case 'f', 'F':
  128. add_bytes(&b, '-' if neg else '+')
  129. // integer, padded with zeros when needed
  130. if digs.decimal_point > 0 {
  131. m := min(digs.count, digs.decimal_point)
  132. add_bytes(&b, ..digs.digits[0:m])
  133. for ; m < digs.decimal_point; m += 1 {
  134. add_bytes(&b, '0')
  135. }
  136. } else {
  137. add_bytes(&b, '0')
  138. }
  139. // fractional part
  140. if prec > 0 {
  141. add_bytes(&b, '.')
  142. for i in 0..<prec {
  143. c: byte = '0'
  144. if j := digs.decimal_point + i; 0 <= j && j < digs.count {
  145. c = digs.digits[j]
  146. }
  147. add_bytes(&b, c)
  148. }
  149. }
  150. return to_bytes(b)
  151. case 'e', 'E':
  152. add_bytes(&b, '-' if neg else '+')
  153. ch := byte('0')
  154. if digs.count != 0 {
  155. ch = digs.digits[0]
  156. }
  157. add_bytes(&b, ch)
  158. if prec > 0 {
  159. add_bytes(&b, '.')
  160. i := 1
  161. m := min(digs.count, prec+1)
  162. if i < m {
  163. add_bytes(&b, ..digs.digits[i:m])
  164. i = m
  165. }
  166. for ; i <= prec; i += 1 {
  167. add_bytes(&b, '0')
  168. }
  169. }
  170. add_bytes(&b, fmt)
  171. exp := digs.decimal_point-1
  172. if digs.count == 0 {
  173. // Zero has exponent of 0
  174. exp = 0
  175. }
  176. ch = '+'
  177. if exp < 0 {
  178. ch = '-'
  179. exp = -exp
  180. }
  181. add_bytes(&b, ch)
  182. switch {
  183. case exp < 10: add_bytes(&b, '0', byte(exp)+'0') // add prefix 0
  184. case exp < 100: add_bytes(&b, byte(exp/10)+'0', byte(exp%10)+'0')
  185. case: add_bytes(&b, byte(exp/100)+'0', byte(exp/10)%10+'0', byte(exp%10)+'0')
  186. }
  187. return to_bytes(b)
  188. case 'g', 'G':
  189. eprec := prec
  190. if eprec > digs.count && digs.count >= digs.decimal_point {
  191. eprec = digs.count
  192. }
  193. if shortest {
  194. eprec = 6
  195. }
  196. exp := digs.decimal_point - 1
  197. if exp < -4 || exp >= eprec {
  198. if prec > digs.count {
  199. prec = digs.count
  200. }
  201. return format_digits(buf, shortest, neg, digs, prec-1, fmt+'e'-'g') // keep the same case
  202. }
  203. if prec > digs.decimal_point {
  204. prec = digs.count
  205. }
  206. return format_digits(buf, shortest, neg, digs, max(prec-digs.decimal_point, 0), 'f')
  207. case:
  208. add_bytes(&b, '%', fmt)
  209. return to_bytes(b)
  210. }
  211. }
  212. /*
  213. Rounds the given decimal number to its shortest representation, considering the provided floating-point format
  214. **Inputs**
  215. - d: The decimal number to round
  216. - mant: The mantissa of the floating-point number
  217. - exp: The exponent of the floating-point number
  218. - flt: Pointer to the Float_Info structure containing information about the floating-point format
  219. */
  220. round_shortest :: proc(d: ^decimal.Decimal, mant: u64, exp: int, flt: ^Float_Info) {
  221. if mant == 0 { // If mantissa is zero, the number is zero
  222. d.count = 0
  223. return
  224. }
  225. /*
  226. 10^(dp-nd) > 2^(exp-mantbits)
  227. log2(10) * (dp-nd) > exp-mantbits
  228. log(2) >~ 0.332
  229. 332*(dp-nd) >= 100*(exp-mantbits)
  230. */
  231. minexp := flt.bias+1
  232. if exp > minexp && 332*(d.decimal_point-d.count) >= 100*(exp - int(flt.mantbits)) {
  233. // Number is already its shortest
  234. return
  235. }
  236. upper_: decimal.Decimal; upper := &upper_
  237. decimal.assign(upper, 2*mant - 1)
  238. decimal.shift(upper, exp - int(flt.mantbits) - 1)
  239. mantlo: u64
  240. explo: int
  241. if mant > 1<<flt.mantbits || exp == minexp {
  242. mantlo = mant-1
  243. explo = exp
  244. } else {
  245. mantlo = 2*mant - 1
  246. explo = exp-1
  247. }
  248. lower_: decimal.Decimal; lower := &lower_
  249. decimal.assign(lower, 2*mantlo + 1)
  250. decimal.shift(lower, explo - int(flt.mantbits) - 1)
  251. inclusive := mant%2 == 0
  252. for i in 0..<d.count {
  253. l: byte = '0' // lower digit
  254. if i < lower.count {
  255. l = lower.digits[i]
  256. }
  257. m := d.digits[i] // middle digit
  258. u: byte = '0' // upper digit
  259. if i < upper.count {
  260. u = upper.digits[i]
  261. }
  262. ok_round_down := l != m || inclusive && i+1 == lower.count
  263. ok_round_up := m != u && (inclusive || m+1 < u || i+1 < upper.count)
  264. if ok_round_down && ok_round_up {
  265. decimal.round(d, i+1)
  266. return
  267. }
  268. if ok_round_down {
  269. decimal.round_down(d, i+1)
  270. return
  271. }
  272. if ok_round_up {
  273. decimal.round_up(d, i+1)
  274. return
  275. }
  276. }
  277. }
  278. /*
  279. Converts a decimal number to its floating-point representation with the given format and returns the resulting bits
  280. **Inputs**
  281. - d: Pointer to the decimal number to convert
  282. - info: Pointer to the Float_Info structure containing information about the floating-point format
  283. **Returns**
  284. - b: The bits representing the floating-point number
  285. - overflow: A boolean indicating whether an overflow occurred during conversion
  286. */
  287. @(private)
  288. decimal_to_float_bits :: proc(d: ^decimal.Decimal, info: ^Float_Info) -> (b: u64, overflow: bool) {
  289. end :: proc "contextless" (d: ^decimal.Decimal, mant: u64, exp: int, info: ^Float_Info) -> (bits: u64) {
  290. bits = mant & (u64(1)<<info.mantbits - 1)
  291. bits |= u64((exp-info.bias) & (1<<info.expbits - 1)) << info.mantbits
  292. if d.neg {
  293. bits |= 1<< info.mantbits << info.expbits
  294. }
  295. return
  296. }
  297. set_overflow :: proc "contextless" (mant: ^u64, exp: ^int, info: ^Float_Info) -> bool {
  298. mant^ = 0
  299. exp^ = 1<<info.expbits - 1 + info.bias
  300. return true
  301. }
  302. mant: u64
  303. exp: int
  304. if d.count == 0 {
  305. mant = 0
  306. exp = info.bias
  307. b = end(d, mant, exp, info)
  308. return
  309. }
  310. if d.decimal_point > 310 {
  311. set_overflow(&mant, &exp, info)
  312. b = end(d, mant, exp, info)
  313. return
  314. } else if d.decimal_point < -330 {
  315. mant = 0
  316. exp = info.bias
  317. b = end(d, mant, exp, info)
  318. return
  319. }
  320. @static power_table := [?]int{1, 3, 6, 9, 13, 16, 19, 23, 26}
  321. exp = 0
  322. for d.decimal_point > 0 {
  323. n := 27 if d.decimal_point >= len(power_table) else power_table[d.decimal_point]
  324. decimal.shift(d, -n)
  325. exp += n
  326. }
  327. for d.decimal_point < 0 || d.decimal_point == 0 && d.digits[0] < '5' {
  328. n := 27 if -d.decimal_point >= len(power_table) else power_table[-d.decimal_point]
  329. decimal.shift(d, n)
  330. exp -= n
  331. }
  332. // go from [0.5, 1) to [1, 2)
  333. exp -= 1
  334. if exp < info.bias + 1 {
  335. n := info.bias + 1 - exp
  336. decimal.shift(d, n)
  337. exp += n
  338. }
  339. if (exp-info.bias) >= (1<<info.expbits - 1) {
  340. set_overflow(&mant, &exp, info)
  341. b = end(d, mant, exp, info)
  342. return
  343. }
  344. decimal.shift(d, int(1 + info.mantbits))
  345. mant = decimal.rounded_integer(d)
  346. if mant == 2<<info.mantbits {
  347. mant >>= 1
  348. exp += 1
  349. if (exp-info.bias) >= (1<<info.expbits - 1) {
  350. set_overflow(&mant, &exp, info)
  351. b = end(d, mant, exp, info)
  352. return
  353. }
  354. }
  355. if mant & (1<<info.mantbits) == 0 {
  356. exp = info.bias
  357. }
  358. b = end(d, mant, exp, info)
  359. return
  360. }