Here's a PySpark program that calculates the area of a circle based on user input for the radius:
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, pow, pi
from pyspark.sql.types import DoubleType
# Create Spark session
spark = SparkSession.builder \
.appName("CircleAreaCalculator") \
.getOrCreate()
# Get radius input from user
radius = float(input("Enter the radius of the circle: "))
# Create a DataFrame with the radius value
df = spark.createDataFrame([(radius,)], ["radius"])
# Calculate the area (πr²)
result = df.withColumn("Area", pi() * pow(df["radius"], lit(2)))
# Show the result
print(f"r = {radius}")
result.select("Area").show(truncate=False)
# Stop Spark session
spark.stop()
Explanation:
-
Spark Session Setup:
- We create a SparkSession which is the entry point to PySpark functionality.
-
User Input:
- The program prompts the user to enter a radius value, which is converted to a float.
-
DataFrame Creation:
- We create a simple DataFrame with one row containing the radius value.
-
Area Calculation:
- Using PySpark's built-in functions:
pi() for the π constant
pow() to square the radius (radius²)
- The formula
πr² is applied to calculate the area
-
Output:
- The program prints the radius and displays the calculated area.
-
Cleanup:
- The Spark session is properly stopped at the end.
Sample Output:
Enter the radius of the circle: 1.1
r = 1.1
+------------------+
|Area |
+------------------+
|3.8013271108436504|
+------------------+
Note: While this demonstrates PySpark functionality, for such a simple calculation, using regular Python would be more efficient. This example is meant to show how you would implement it in PySpark, which would be more relevant when working with distributed data processing.