HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Convert "String" sqrt(#) into numerical value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertintonumericalvaluesqrtstring

Problem

I had to come up with a way to convert sqrt(#) into its actual numeric value because before I would have an array containing elements such as:

[sqrt(3), -sqrt(3), 1]


If I tried to multiply, I would get the error:


Argument "-sqrt(3)" isn't numeric in multiplication (*)

Here is my work-around, but I think there's a better way. Any suggestions?

#!/usr/bin/perl
#perl Solver.pl

use strict;
use warnings;

my $roots = "Sqrt[3] ||-Sqrt[3] ||1";
my @rootList = split(/ \|\|/, $roots); # fill array with string's values separated by " ||"

# Convert any Sqrt numbers to numerical value 
# (ex.) Sqrt[3] -> sqrt(3)
for $_ ( @rootList ){
    $_ =~ s/Sqrt\[/sqrt(/g; # Sqrt[ -> sqrt(
    $_ =~ s/\]/)/g; # ] -> )

    if( $_ =~ /-sqrt/ ){ # replace string of negative sqrt()
        my $temp = substr( $_, 6 ); # take "#)"
        $temp =~ s/\)//g; # remove ")"
        $_ = -1*sqrt( $temp );
    }
    elsif( $_ =~ /sqrt/ ){ # replace positive sqrt()
        my $temp = substr( $_, 5 );
        $temp =~ s/\)//g;
        $_ = sqrt( $temp );
    }
}

print "[@rootList]\n";

Solution

I found the use of Sqrt[...] to be cumbersome, why have the case in that format, and why have the [] style braces?

I would normally not recommend this, but a simple solution, if you trust, or can sanitize your inputs, is to just use the eval function.

for $_ ( @rootList ){
    $_ =~ s/Sqrt\[(.+)\]/sqrt($1)/;
    $_ = eval($_);
    $@ and die $@;
}


That does it..... all of it. Convert Sqrt[...] to sqrt(...), and eval the result.

Code Snippets

for $_ ( @rootList ){
    $_ =~ s/Sqrt\[(.+)\]/sqrt($1)/;
    $_ = eval($_);
    $@ and die $@;
}

Context

StackExchange Code Review Q#93167, answer score: 3

Revisions (0)

No revisions yet.