Question: using genetic algorithms find the python code to calculate all the real - valued intersection points of the following three functions: f 1 ( x

using genetic algorithms find the python code to calculate all the real-valued intersection points of the following three functions:
f1(x)= x +1, f2(x)= x^2 and f3(x)= x^5+1.
Current Code:
# Genetic algorithm
# - various problem types
# - various chromosome types
import random
import math
# Create a chromosome
def create_chromosome(length, gene_type='real', gene_range=(-2,2),**kwargs):
if gene_type == 'binary':
return [random.randint(0,1) for _ in range(length)]
elif gene_type == 'integer':
return [random.randint(gene_range[0], gene_range[1]) for _ in range(length)]
elif gene_type == 'real':
return [random.uniform(gene_range[0], gene_range[1]) for _ in range(length)]
# Create the initial population
def create_population(pop_size, chrom_length, gene_type='real', gene_range=(-2,2)):
return [create_chromosome(chrom_length, gene_type, gene_range) for _ in range(pop_size)]
# Fitness function for max bits problem: maximise the number of 1's in a binary string
def fitness_max_bits(chromosome):
optimal_value = len(chromosome) # The best case is when all bits are 1
return optimal_value - sum(chromosome) # Distance from the optimal value, 0 being the best
def fitness_intersection(chromosome):
x = chromosome[0]
f1= x +1
f2= x**2
f3= x**5+1
fitness_value =1/(1+ abs(f1- f2)+ abs(f1- f3)+ abs(f2-f3))
return abs(fitness_value-1)
# Selection function - choose 2 at random and select the one with fitness closest to 1
def selection(population, fitness_fn=fitness_closest_to_one):
selected = random.sample(population,2) # Randomly select two individuals
return min(selected, key=fitness_fn) # Return the one with the fitness value closest to 1
# Crossover function
def crossover(parent1, parent2, gene_type='real', crossover_rate=0.7):
if random.random()< crossover_rate:
if gene_type == 'binary':
# Single-point crossover for binary chromosomes
crossover_point = random.randint(1, len(parent1)-1)
return parent1[:crossover_point]+ parent2[crossover_point:]
elif gene_type == 'integer':
# Single-point crossover for integer chromosomes to avoid generating floats
crossover_point = random.randint(1, len(parent1)-1)
return parent1[:crossover_point]+ parent2[crossover_point:]
elif gene_type == 'real':
# Blending for real-valued chromosomes
return [(p1+ p2)/2 for p1, p2 in zip(parent1, parent2)]
return parent1 if random.random()<0.5 else parent2
# Mutate a chromosome
def mutate(chromosome, mutation_rate=0.01, gene_type='real', gene_range=(-2,2)):
if gene_type == 'real':
return [gene if random.random()> mutation_rate else gene + random.uniform(-0.1,0.1) for gene in chromosome]
if gene_type == 'binary':
return [gene if random.random()> mutation_rate else 1- gene for gene in chromosome]
elif gene_type == 'integer':
return [gene if random.random()> mutation_rate else random.randint(gene_range[0], gene_range[1]) for gene in chromosome]
return chromosome
# Create the next generation
def create_next_generation(population, fitness_fn, crossover_rate=0.7, mutation_rate=0.01, gene_type='real', gene_range=(-2,2)):
next_generation =[]
for _ in range(len(population)):
parent1= selection(population, fitness_fn)
parent2= selection(population, fitness_fn)
offspring = crossover(parent1, parent2, gene_type, crossover_rate)
mutated_offspring = mutate(offspring, mutation_rate, gene_type, gene_range)
next_generation.append(mutated_offspring)
return next_generation
# Output the initial population
def print_initial_population(population, fitness_fn, gene_type):
print("Initial Population:")
for i, individual in enumerate(population):
if gene_type == 'real':
# Print real values with four decimal places
chromosome_str =','.join(f"{gene:.4f}" for gene in individual)
elif gene_type == 'integer':
# Print integer values
chromosome_str =','.join(f"{gene}" for gene in individual)
elif gene_type == 'binary':
# Print binary values (0 or 1)
chromosome_str =''.join(str(gene) for gene in individual)
else:
chromosome_str =','.join(str(gene) for gene in individual)
print(f"Individual {i+1}: [{chromosome_str}], Fitness ={fitness_fn(individual):.4f}")
print("---")
# Perform the genetic algorithm
# Perform the genetic algorithm
def genetic_algorithm(pop_size, chrom_length, fitness_fn, generations, gene_type='real', gene_range=(-2,2), crossover_rate=0.7, mutation_rate=0.01):
population = create_population(pop_size, chrom_length, gene_type, gene_range)
#

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!