求等價於求等價於求令則牛頓的迭代程式碼如下:double cuberoot(double t){ double x = 1000, t2 = abs(t), ex = 0.0000001; while (abs(x * x * x - t2) > ex){ x = x - (x * x * x * x - t2 * x) / (5 * x * x * x - 2 * t2); } return t > 0 ? x : -x;}最後,還給出了一個二分法求立方根,時間複雜度與牛頓差不多,都是log級,程式碼如下:double cuberoot(double t){ double l = -1000, r = 1000, x = (l + r) / 2, ex = 0.0000001; while (1){ double a = x * x * x - t; if (a<ex && a>-ex) break; if (a > ex) r = x; else l = x; x = (l + r) / 2; } return x;}
求等價於求等價於求令則牛頓的迭代程式碼如下:double cuberoot(double t){ double x = 1000, t2 = abs(t), ex = 0.0000001; while (abs(x * x * x - t2) > ex){ x = x - (x * x * x * x - t2 * x) / (5 * x * x * x - 2 * t2); } return t > 0 ? x : -x;}最後,還給出了一個二分法求立方根,時間複雜度與牛頓差不多,都是log級,程式碼如下:double cuberoot(double t){ double l = -1000, r = 1000, x = (l + r) / 2, ex = 0.0000001; while (1){ double a = x * x * x - t; if (a<ex && a>-ex) break; if (a > ex) r = x; else l = x; x = (l + r) / 2; } return x;}