我正在使用Zarith库来进行任意精度的有理算术.假设我有一个有理数q的类型Q.t,即两个大整数的比率(Q是Zarith的任意精度有理数模块).有时,为了便于阅读,我想将此数字打印为浮点数,有时我需要将此数字浮点数转换为以后的非任意精度计算.有没有办法将q浮点数转换为一定的精度?
我转换q为浮点的方式现在无法保证,并且可以创建未定义的浮点数(Z是任意精度整数模块):
let to_float q =
let n, d = num q, den q in
(* check if d is zero and raise an error if it is *)
let nf, df = Z.to_float n, Z.to_float d in
nf /. df
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来处理这个问题,我可以获得最准确接近任何浮点数的浮点数q?
编辑
如果有人有兴趣,我很快就会在OCaml中写下Mark Dickinson的回答.它可能(绝对)可以改进和清理.如果我这样做,或者如果有人有任何改进建议,我会编辑.但是现在这已经解决了我的问题!
let to_float q =
let n, d = num q, den q in
let n_sign = Z.sign n in …Run Code Online (Sandbox Code Playgroud) 我有一个文件,其中每一行是一个json对象,如下所示:
{"name": "John", ...}
{...}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用相同的对象创建一个新文件,但从所有这些文件中删除了某些属性.
当我这样做时,我得到一个UnicodeEncodeError.奇怪的是,如果我改为循环range(n)(对于某些数字n)并使用infile.next()它,它就像我想要的那样工作.
为什么这样?如何通过迭代来实现这一点infile?我尝试使用dumps()而不是dump(),但这只是在一堆空行outfile.
with open(filename, 'r') as infile:
with open('_{}'.format(filename), 'w') as outfile:
for comment in infile:
decodedComment = json.loads(comment)
for prop in propsToRemove:
# use pop to avoid exception handling
decodedComment.pop(prop, None)
json.dump(decodedComment, outfile, ensure_ascii = False)
outfile.write('\n')
Run Code Online (Sandbox Code Playgroud)
这是错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\U0001f47d' in position 1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!