LESSON 34 OF 52 · CHAPTER 04

Float Refinement

Newton-style square-root refinement, bounded steps, typed contracts

ORIGINAL SOURCE

10-float-refinement.srp

// Newton refinement uses float values and an integer iteration count.
pure funcra root(value: float, steps: integer = 6) -> float
    needs value > 0.0;
    needs steps >= 0;
    ensures result > 0.0;
{
    var estimate = 1.0;
    repeat steps as iteration {
        estimate = (estimate + value / estimate) / 2.0;
    }
    return estimate;
}

bind sqrt2 = root(2.0);
print("sqrt2 checked", sqrt2 > 1.414 and sqrt2 < 1.415);
print("sqrt9", root(9.0));
EXPECTED OUTPUT

stdout

Verified
sqrt2 checked true
sqrt9 3.0

UNDERSTAND THE CODE

Explanation & practice

What this example teaches

Newton-style square-root refinement, bounded steps, typed contracts

Expected behavior

sqrt2 checked true, then sqrt9 3.0

Practice: Read the source before looking at the output. Predict the values and their order, then use the pinned compiler to execute this lesson and compare the exact fixture. Identify which operation produces the result.

दशमलव में न्यूटन विधि

pure funcra root किसी सकारात्मक मान का वर्गमूल अनुमानित करता है। repeat के साथ निर्धारित संख्या में सुधार होता है; needs मान और चरणों की पूर्वशर्तें देता है, ensures परिणाम सकारात्मक होने की शर्त रखता है। √2 को एक दायरे में जाँचा जाता है, पूर्णतः बराबर नहीं माना जाता।

आउटपुट: sqrt2 checked true और sqrt9 3.0।

अभ्यास: सकारात्मक इनपुट की पूर्वशर्त क्यों आवश्यक है? डिफ़ॉल्ट steps कितना है?

Explanations are sourced from the project's English chapter guide and हिन्दी अध्याय. The Scarp program and output are unchanged.

TRY IT LOCALLY

Verify, then execute

Use the pinned compiler from the course root. Keep any imported _support files next to the source.

scarp verify examples/04-collections/10-float-refinement.srp scarp exec examples/04-collections/10-float-refinement.srp

The website does not run code. Read the CLI guide ↗

Pinned compiler: Scarp v0.0.6-alpha.3 · ceff07d9014f. No simulated output.