/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.awk.builtin;

import java.math.BigInteger;

import net.morilib.awk.misc.Math2;
import net.morilib.awk.value.AwkFloat;
import net.morilib.awk.value.AwkInteger;
import net.morilib.awk.value.AwkValue;

/**
 * 組み込み関数sqrtの記述です。
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/04/13
 */
public class AwkSqrt extends AwkMathFunction2 {

	protected AwkSqrt() {
		super("sqrt");
	}

	@Override
	protected double f(double x) {
		return Math.sqrt(x);
	}

	@Override
	protected AwkValue f(BigInteger x) {
		BigInteger[] q;

		if(x.signum() < 0) {
			return AwkFloat.valueOf(Double.NaN);
		} else {
			q = Math2.sqrtExact2(x);
			if(q[1].signum() == 0) {
				return AwkInteger.valueOf(q[0]);
			} else {
				return AwkFloat.valueOf(Math.sqrt(x.doubleValue()));
			}
		}
	}

}
