druant 2021-04-19 16:58 采纳率: 0%
浏览 381

TypeError: '>' not supported between instances

用Pycharm实现梯度下降法求余弦曲线的极小值出现了line 13, in <module>
    while deta_h< error_rate:
TypeError: '<' not supported between instances of 'tuple' and 'float'

这是代码 ,怎么改,求解,快哭了,小白

import math
import numpy as np

def f(x):
 return  0.03693* math.sin ( 1.165 *x- 1.538 ), math .sin (1.165 *x- 1.538)
def h(x):
 return 1.165*0.03693*math.cos(1.165*x-1.538), math .cos (1.165 *x- 1.538)
a = 4.32517219917013  #  初始点(初始横坐标)
step = 0.01  #(步长)
count =0 # 记录迭代次数
deta_h = h(a) # a更新前后的差值(初始值设定为起始点,也可以设置为大于阈值的任意的数)
error_rate = 1e-5 # 给定的阈值
while deta_h< error_rate: # 这里怎么改,求解。
    b = a-step* h(a) # 更新a,用新的变量接收
deta_h = np.abs(h(b)-h(a))
count += 1
a = b-step*h(b)
y = f( b )

print('迭代次数%d'%count)
print(a)
print(y)
print('极值点为(%f,%f)'%(a,  y ))
  • 写回答

2条回答 默认 最新

  • CSDN专家-HGJ 2021-04-19 17:11
    关注

    因为f 和h两个函数返回的均为元组类型数据,不能与标量直接运算或比较,要么用索引去获取其中一个值,要么在函数内进行计算后返回一个值供后续调用。

    import math
    import numpy as np
    
    
    def f(x):
     return 0.03693 * math.sin(1.165 * x - 1.538)
    
    
    def h(x):
     return 1.165*0.03693*math.cos(1.165*x-1.538)
    
    
    a = 4.32517219917013  # 初始点(初始横坐标)
    step = 0.01  # (步长)
    count = 0  # 记录迭代次数
    deta_h = h(a)  # a更新前后的差值(初始值设定为起始点,也可以设置为大于阈值的任意的数)
    print(deta_h)
    error_rate = 1e-5  # 给定的阈值
    while deta_h < error_rate:  # 这里怎么改,求解。
        b = a-step * h(a)  # 更新a,用新的变量接收
        
        deta_h = np.abs(h(b)-h(a))
        count += 1
        a = b-step*h(b)
        y = f(b)
    
        print('迭代次数%d' % count)
        print(a)
        print(y)
        print('极值点为(%f,%f)' % (a,  y))
    """
    计算结果:
    ...
    迭代次数265
    4.527065718292443
    -0.020669715062149065
    极值点为(4.527066,-0.020670)
    """
    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择