# -*- coding: utf-8 -*-
"""problem 2 class 4 offline

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/10n45tcpjVcRcO65S-6hJK2_trgI091yp
"""

# libraries
import random 
import math
import numpy as np 
import matplotlib.pyplot as plt
random.seed(10)

def integral(N):
  A= 0
  B = 8
  # lists for storing the values
  y1_values = []
  y1_square_values =[]

  y2_values =[]
  y2_square_values =[]

  count_1 = 0
  count_2 = 0 

  for i in range(1,N+1):
    # x random value generation
    x = random.uniform(A,B)
    # calculating first area value
    if x <=4 : 
      y1 = math.sqrt(4 * x)
      y1_values.append(y1)
      y1_square_values.append(y1*y1)
      count_1 += 1 
    else: 
      y2 = 8 - x
      y2_values.append(y2)
      y2_square_values.append(y2*y2)
      count_2 += 1 

  # calculate 0 to 4 area first part
  y1_average = sum(y1_values) / len(y1_values)
  y1_square_average = sum(y1_square_values) / len(y1_square_values)
  area_1 = y1_average * ( 4-0 )
  error_1 = ( (4-0) / math.sqrt(count_1) ) * math.sqrt(y1_square_average - y1_average**2)

  # calculate 4 to 8 area second part
  y2_average = sum(y2_values) / len(y2_values)
  y2_square_average = sum(y2_square_values) / len(y2_square_values)
  area_2 = y2_average * ( 8-4 )
  error_2 = ( (8-4) / math.sqrt(count_2) ) * math.sqrt(y2_square_average - y2_average**2)

  #total area and error
  integral_value = area_1 + area_2 
  error_estimate = error_1 + error_2 
  
  print("For number of sample points: ", N)
  print("Integral Value: ", integral_value)
  print("Estimated Error: ", error_estimate)
  print("")

N = [100,1000,5000,10000]
for i in N:
  integral(i)