[英]Python round() to remove trailing zeros
下面的代碼用於使用梯度下降找到x*
,這里的問題是-1.00053169969469
req8
當我將它四舍五入時,它會導致-1.00000000000000
。
如何在不使用任何其他模塊的情況下舍入以得到-1.0
或-1.00
?
from sympy import *
import numpy as np
global x, y, z, t
x, y, z, t = symbols("x, y, z, t")
def req8(f, eta, xi, tol):
dx = diff(f(x), x)
arrs = [xi]
for i in range(100):
x_star = arrs[-1] - eta * round(dx.subs(x, arrs[-1]), 7)
if abs(dx.subs(x, x_star)) < tol:
break
arrs.append(x_star)
print(arrs[-1])
print(round(arrs[-1], 2))
def f_22(x):
return x**2 + 2*x - 1
req8(f_22, 0.1, -5, 1e-3)
使用format
function 打印帶有所需位數的四舍五入結果(在下面的示例中為 2):
print("{:.2f}".format(round(arrs[-1], 2)))
編輯:正如@SultanOrazbayev 所指出的,這里不再需要舍入,您可以使用以下表達式打印結果:
print("{:.2f}".format(arrs[-1]))
num1 = 1.233455768
#Use round() function
print(round(num1,2))
#Use format method
print('{:.2f}'.format(num1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.