writefln("square root of %f is %f", 0.000076, ret);
ret = sqrt(123456, 500);
writefln("square root of %d is %f", 123456, ret);
}
/** Newton’s method で平方根を求める */ import std.stdio; import std.math; const float GOOD_ENOUGH = 0.0001; const int TOO_SLOW = 100; float sqrt(float value, float guess) { if (value == 0) { return 0; } else if (value < 0) { writefln("Value must be positive."); return -1; } if (guess <= 0) { guess = 1; } int round = 0; float next = (guess + value / guess) / 2; while (abs(next - guess) /guess > GOOD_ENOUGH && round < TOO_SLOW) { round++; guess = next; next = (guess + value / guess) / 2; } return guess; } void main() { float ret = sqrt(2, 1); writefln("square root of %d is %f", 2, ret); ret = sqrt(0.000076, 0.008); writefln("square root of %f is %f", 0.000076, ret); ret = sqrt(123456, 500); writefln("square root of %d is %f", 123456, ret); }
ソースをコンパイルし、実行した結果です。
uprush@uprush-dev:~/src/d/sicp$ dmd newton.d
uprush@uprush-dev:~/src/d/sicp$ ./newton
square root of 2 is 1.414216
square root of 0.000076 is 0.008718
square root of 123456 is 351.363678