【发布时间】:2020-05-06 02:10:16
【问题描述】:
我尝试在 python 中求解摩擦系数的 colebrook(非线性)方程,但我不断收到此错误:
Traceback (most recent call last):
File "c:/Users/WWW/Desktop/WWWWWWWW/WWWWWWWWWWW/DDD/WWWWW.py", line 46, in <module>
F_factor = Newton(f=0.1)
File "c:/Users/WWW/Desktop/WWWWWWWW/WWWWWWWWWWW/DDD/WWWWW.py", line 22, in Newton
eps_new = float(func(f))/dydf(f)
TypeError: only size-1 arrays can be converted to Python scalars
我知道出了点问题,但不确定是什么。
我正在尝试找到这个equation 的摩擦系数 (f)
-0.86 * log(2.51 / (Re * sqrt(f)) + e / D / 3.7) = 1 / sqrt(f)
在雷诺数 Re 的不同值下并绘制 f 对 Re。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import time
#Parameters
e_D = 1e-4
Re = np.linspace(10**4,10**7,10)
eps=1e-7
def func(f):
return -0.86*np.log((e_D/3.7)+(2.51/Re)*f**0.5)-f**0.5
def dydf(f):
return (((-1.255/Re)*f**-1.5)/((e_D/3.7)+((2.51/Re)*f**-0.5)))-((f**-1.5)/1.72)
def Newton(f,conv_hist=True):
eps_new = float(func(f))/dydf(f)
#y_value = func(f)
iteration_counter = 0
history = []
while abs(eps_new) >= eps and iteration_counter < 100:
eps_new = float(func(f))/dydf(f)
f = f - eps_new
#y_value = func(f)
iteration_counter += 1
history.append([iteration_counter, f, eps_new])
# Here, either a solution is found, or too many iterations
if abs(dydf(f)) <= eps:
print('derivative near zero!, dydf =', dydf)
print(func(f), 'iter# =', iteration_counter, 'eps =', eps_new)
break
if conv_hist:
hist_dataframe = pd.DataFrame(history, columns=['Iteration #', 'f', 'eps'])
print(hist_dataframe.style.hide_index())
return f, iteration_counter
startTime = time.time()
F_factor = Newton(f=0.1)
endTime = time.time()
print(F_factor)
print('Total process took %f seconds!' % (endTime - startTime))
plt.loglog(F_factor, Re, marker='o')
plt.title('f vs Re')
plt.grid(b=True, which='minor')
plt.grid(b=True, which='major')
plt.xlabel('Re')
plt.ylabel('f')
plt.savefig('fvsRe.png')
plt.show()
【问题讨论】:
-
能否包含整个错误回溯?
-
我刚刚添加了整个错误回溯。谢谢!
标签: python numpy matplotlib typeerror newtons-method