generic_float.odin 9.5 KB

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