/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   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 org.bodington.statistics;

import org.apache.log4j.Logger;

import java.io.*;

public class TDistribution extends java.lang.Object
	{
    
    private static Logger log = Logger.getLogger(TDistribution.class);
    
	public static double p( double t, double df )
		{
		boolean dfeven;
		double p, theta, cos2theta, nthterm, twothetapi;
		

		theta = Math.atan( t/Math.sqrt( df ) );
		cos2theta = Math.cos( theta );
		cos2theta = cos2theta*cos2theta;

		dfeven=(((int)df)%2)==0;
		
		if ( dfeven )
			{
			nthterm=1.0;
			p=1.0;
			for ( int i=2; i<df; i+=2 )
				{
				nthterm=nthterm*(i-1)/i*cos2theta;
				p+=nthterm;
				}
			p=Math.sin( theta ) * p;

			return 1.0-p;
			}
		
		twothetapi=2.0*theta/Math.PI;
		if ( df==1.0 )
			{
			return 1.0-twothetapi;
			}

		nthterm=1.0;
		p=1.0;
		for ( int i=2; i<(df-1); i+=2 )
			{
			nthterm=nthterm*i/(i+1)*cos2theta;
			p+=nthterm;
			}
		p=2.0/Math.PI * Math.cos( theta ) * Math.sin( theta ) * p + twothetapi;

		return 1.0-p;
		}

	public static void main ( String arg[] )
		{
		String strt, strdf;
		Double t, df;
		DataInputStream datain=new DataInputStream( System.in );

		try
			{
			log.debug( "t>" );
			strt=datain.readLine();
			log.debug( "df>" );
			strdf=datain.readLine();
			}
		catch ( IOException ioex )
			{
			log.warn( ioex.getMessage() );
			return;
			}
		
		t = new Double( strt );
		df = new Double( strdf );
		
		log.debug( "p=" + p( t.doubleValue(), df.doubleValue() ) );
		}
		
	
	}




