You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab中二分法Python代码print语句语法错误求助

问题解决:二分法代码的语法错误

嘿,这问题很常见——你踩了Python2和Python3语法差异的坑啦!

错误原因

Google Colab默认使用Python3环境,而Python3里的print是内置函数,必须用括号把要输出的内容括起来。你最后一行写的是Python2的语法:

print intercept_bisection(f, 0.001)

这在Python3里会直接触发语法错误,因为它不再是语句,而是需要调用的函数。

修正方法

把最后一行改成带括号的Python3写法就行:

print(intercept_bisection(f, 0.001))

修正后的完整代码

# bisection method

def f(x):
    return -5+2*x

def intercept_bisection(func, epsilon):
    ''' func is a function
        epsilon is some small float
    '''
    low = 0
    high = 100
    mid = (high + low)/2.0

    while (abs(func(mid)) > epsilon):
        print("low = ", low, "high = ", high, "mid = ", mid)
        if func(mid) > 0:
            high = mid
        elif func(mid) < 0:
            low = mid
        mid = (high + low)/2.0
    return mid

print(intercept_bisection(f, 0.001))

运行结果说明

函数f(x) = -5 + 2x的零点是x=2.5,用epsilon=0.001运行修正后的代码,会输出一个接近2.5的数值(比如2.5009765625),符合二分法的逼近效果。

内容的提问来源于stack exchange,提问作者Wei Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:14:40