Calculate sqrt(a^2 + b^2) without under overflow. - CSharp System

CSharp examples for System:Math Number

Description

Calculate sqrt(a^2 + b^2) without under overflow.

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
using System;/* w w  w  . jav  a 2  s. co m*/

public class Main{
        /// <summary>
        /// Calculate sqrt(a^2 + b^2) without under/overflow.
        /// </summary>
        /// <param name="a">The a value.</param>
        /// <param name="b">The b value.</param>
        /// <returns>The result.</returns>
        public static double Hypot(double a, double b)
        {
            double r;
            if (Math.Abs(a) > Math.Abs(b))
            {
                r = b/a;
                r = Math.Abs(a)*Math.Sqrt(1 + r*r);
            }
            else if (b != 0)
            {
                r = a/b;
                r = Math.Abs(b)*Math.Sqrt(1 + r*r);
            }
            else
            {
                r = 0.0;
            }
            return r;
        }
}

Related Tutorials