MecSimCalc
ExploreSearchCreateDocsCommunityBlogPricing
    Apps

    Starred
    Go to app
    App Docs

Documentation of How to use Complex Number


Usage:

You can use this app to compute matematical problems on complex numbers easily.

If you are curious, you can also graph a complex function. For the graphing of complex number I used the solution complex domain coloring, Domain coloring makes every input complex number a point on a 2D graph, and every output complex number a color. It then colors each input point with its cooresponding output color. It's magnitude means point's distance from the orgin becomes it's brightness and the argument of the resulting complex number is hue.


How to use the Complex Number Solver

Input:

First of all input the mathematical expression you want to solve containing a complex number in the Mathematical Expression Field. and then press Enter.

You will Immediately see the answer of the expression.

Output:

How to write a Mathematical expression

  1. Use sin(), cos(), tan() for trignometric functions.
  2. use ^ or ** to denote power of a number
  3. * for multiply, + for plus, - for minus and / for divide

Example: tan(3 + 4i) - 2^3



How to use Complex Function Grapher

Input:

You can input any mathematical function in the input field containing a complex number variable z You can also set the range of graph's x-axis.

Be sure to check the Graph Function checkbox if you want to graph a complex function. By default it's unchecked.



Output:

It will graph your function as follows:

centre of the graph is complex number 0 + 0i . By going right from center, the real part increases and by going left it decreases and similarly by going to top the imaginary part increases and by going to bottom it decreases.



Functions to try

f(z) = 1/z

f(z) = log(z)

f(z) = sin(z)

f(z) = tan(z)


Bonus

This app also provides you with a random but cool trick to solve mathematical computations on complex numbers.


Credits

My project uses cmath python library for complex number calculations. I used Pillow library to make graph of complex functions on an image.

This project is inspired from a project by Dan Jutan.

Complex Function Grapher by Dan Jutan: https://jutanium.github.io/ComplexNumberGrapher/


Source Code

import base64
import io
import math
from PIL import Image, ImageDraw, ImageColor
import cmath
import random



# This function is used to create an image from the plot created using matplotlib.plt
def plt_show(plt, width=500, dpi=100):
    # Converts matplotlib plt to data string
    # dpi (dots per inch) is the resolution of the image
    # width is width of image in pixels
    bytes = io.BytesIO()
    plt.savefig(bytesformat='png', dpi=dpi)  #  Save as png image
    plt.close()
    bytes.seek(0)
    base64_string = "data:image/png;base64," + \
        base64.b64encode(bytes.getvalue()).decode("utf-8")
    return " + base64_string + "' width='" + str(width) + "'>"


# Function to embed a image
def Image_Embed(data):
    return " + data + "' width='600' style='margin: auto;'>"



# Calculate magnitude and theta of a complex number
def calculate_mag_deg(z):
    a = z.real
    b = z.imag
    r = math.hypot(a, b)
    theta = math.degrees(math.atan2(b, a))
    if theta < 0:
        theta += 360


    return {
        "magnitude"round(r, 2),
        "degrees"round(theta, 2)
    }


# Make a function string evaluatable by python.
def make_function_evaluatable(func):
    return func.replace("log""cmath.log").replace("logn""cmath.logn").replace("pi""cmath.pi").replace("sin""cmath.sin").replace("cos""cmath.cos").replace("tan""cmath.tan").replace("^""**").replace("i""j").replace("sjn""sin").replace("pj""pi")


# Solve function: solve string function on input of complex number z and return answer
def solve_function(function, z):
    # make function evaluatable
    function = make_function_evaluatable(function)


    # replace z with the  complex number z
    function = function.replace("z"str(z))


    try:
        # securely evaluate the expression
        return eval(function, {"__builtins__": {}}, {"cmath": cmath})
    except:
        return 0



# solve mathematical expressions containing complex numbers
def solve_expression(exp):
    exp = make_function_evaluatable(exp)


    try:
        # securely evaluate the expression
        return eval(exp, {"__builtins__": {}}, {"cmath": cmath})
    except:
        # If any errors return False
        return False



# graph complex numbers using complex domain coloring on a png image
def graph_complex_function(f, a, b):
    points = []


    # compute magnitude and degrees for every imaginary number on graph
    for i in range(a, b+1):
        col = []
        for j in range(a, b+1):
            z = complex(i, j)
            solved = solve_function(f, z)
            calc = calculate_mag_deg(solved)
            col.append({
                "magnitude": calc["magnitude"],
                "degrees": calc["degrees"]
            })


        points.append(col)


    w = abs(a) + abs(b) + 1;
    print(w)
    img = Image.new("RGB", (w, w))
    draw = ImageDraw.Draw(img)


    # draw every pixel in the image
    for i in range(w):
        for j in range(w):
            # calculate the brightness for the point
            l = abs(math.atan(abs(points[i][j]["magnitude"])) / (math.pi / 2) * 100)
            # color hue
            d = abs(points[i][j]["degrees"])
            # make color in hsl format
            color = f"hsl({d}, 100%, {l}%)"


            draw.point((i, j), fill=ImageColor.getrgb(color))


    # save image as png and show 
    img = img.transpose(method=1)
    buffer = io.BytesIO()
    print(img.format)
    img.save(buffer, format="PNG")
    encoded_data = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
    image = Image_Embed(encoded_data)
    return image


# Generates a random trick for solving complex numbers
def generate_random_trick():
    # tricks to solve complex numbers
    tricks = [
        {
            "heading""Powers of i",
            "trick""i2 = -1 
 i3 = -i 
 i4 1"
        },         {             "heading""Multiplying Conjugates",             "trick""(a + bi)(a - bi) = a2 + b2"         },         {             "heading""Multiplication",             "trick""(a + bi)(c + di) = (ac - bd) + (ad + bc)i"         },         {             "heading""Addition",             "trick""(a + bi) + (c + di) = (a + c) + (b + d)i"         },         {             "heading""Subtraction",             "trick""(a + bi) - (c + di) = (a - c) + (b - d)i"         },         {             "heading""Division",             "trick""(a + bi)/(c + di) = (ac + bd/c2 + d2) + (bc - ad/c2 + d2)i"         }     ]     return random.choice(tricks) def main(inputs):     f = inputs['func']     a = inputs['range'][0]     b = inputs['range'][1]     graph_function = inputs['graph_function']     expression = inputs['math_exp']     err_solve = False     err_graph = False     image = False     if graph_function:         # check if function is valid         if "z" not in f:             err_graph = True             image = False         else:             image = graph_complex_function(f, a, b)     else:         image = False     solved = solve_expression(expression)     # check for errors in solving expression     if solved == False:         err_solve = True     details = calculate_mag_deg(solved)     return {         "equation": f,         "a": a,         "b": b,         "Image": image,         "math_exp": expression,         "solved"str(solved).replace("j""i"),         "modulus": details["magnitude"],         "argument": details["degrees"],         "trick": generate_random_trick(),         "err_solve": err_solve,         "err_graph": err_graph,         "graph_function": graph_function     }
Similar apps:
Math
Calculator
Civil Engineering
Comp11052022
Complex Numbers
Math
Maths

Copyright © MecSimCalc 2024
Terms | Privacy