Perl sqrt, cube issue: 1 showing up after each line - shell

I am having a tiny issue with a small perl script using arithmetic operators. After my cube root, and square root operators, a 1 shows up. I was testing this script on an openSUSE 42.1 VM.
I'm just not too certain what the 1 after each line is, I have tried looking it up, but am not too certain. I mainly script in bash, and ksh, so this perl syntax is a bit new to me.
Script:
#!/usr/bin/perl
# Provide a sum, cube of the sum, and square root of the sum of three set variables
# Set variables
$v1=10;
$v2=9;
$v3=8;
$val=$v1+$v2+$v3;
$cube=$val ** (1/3);
$square= sqrt($val);
print "Sum of 10, 9, 8: $val\n";
print
print "Cube of Sum: $cube\n";
print
print "Square of Sum: $square\n";
print
print "Thanks for using this script!"

Your lines just saying
print
are not statements in themselves as they are not terminated by a ;. Instead they are part of statements of the form
print print "text";
The inner print has an argument of "text" and prints that, the outer print has an argument of print "text" and print the value of that, and when succesful print returns a value of 1 (perldoc only says it returns true, so don't rely it being 1) - so a 1 is printed.
If the point was to format your output nicely, you should explicitly print "\n".

As has been explained, half of your print calls are printing the return value of the following print statement because you are missing a semicolon at the end of the line to terminate the statement
Also, print on its own will print the value of the default variable $_, not a newline as you expected. You need to write print "\n"; to achieve what you intend
It's also very important to add use strict and use warnings 'all' to the top of every Perl program you write. You will also need to declare all of your variables using my
#!/usr/bin/perl
use strict;
use warnings 'all';
# Provide a sum, cube of the sum, and square root of the sum of three set variables
# Set variables
my $v1 = 10;
my $v2 = 9;
my $v3 = 8;
my $val = $v1 + $v2 + $v3;
my $cube = $val**( 1 / 3 );
my $square = sqrt($val);
print "Sum of 10, 9, 8: $val\n";
print "\n";
print "Cube root of Sum: $cube\n";
print "\n";
print "Square root of Sum: $square\n";
print "\n";
print "Thanks for using this script!\n";
print "\n";
output
Sum of 10, 9, 8: 27
Cube root of Sum: 3
Square root of Sum: 5.19615242270663
Thanks for using this script!
It's also worth pointing out that there's a construct called a here document that will let you do this more neatly and clearly. If you change those print statements to just one, like this, then the intention is clear and the output is identical to that of the original code
print <<END;
Sum of 10, 9, 8: $val
Cube root of Sum: $cube
Square root of Sum: $square
Thanks for using this script!
END

As Henrik states in his answer, the lines with print and no ; are the problem.
An alternate way to get Perl to print a blank line between the main lines of output is to add an addition new line character, \n, at the end of each of the print lines. The code would become:
#!/usr/bin/perl
# Provide a sum, cube of the sum, and square root of the sum of three set variables
# Set variables
$v1=10;
$v2=9;
$v3=8;
$val=$v1+$v2+$v3;
$cube=$val ** (1/3);
$square= sqrt($val);
print "Sum of 10, 9, 8: $val\n\n";
print
print "Cube of Sum: $cube\n\n";
print
print "Square of Sum: $square\n\n";
print
print "Thanks for using this script!"
The output is:
Sum of 10, 9, 8: 27
Cube of Sum: 3
Square of Sum: 5.19615242270663
By the way, your equation for calculating the cube of the sum calculates the cubed root. To calculate the cube of the sum you need,
$cube=$val ** (3);
Likewise, your equation to find the square of the sum is calculating the square root, not the square. To find the square of the sum you need to raise the sum to the power of 2.

Related

How to generate and sum up a sequence

Basically, what I'm trying to understand is that how to reassign a variable that was already declared before to a new value.
I want to reassign the variable to a different value in the loop. Then print that sum.
For example in JavaScript,
sum = 0;
for... (loop)
sum = sum + start-point; (loop body)
console.log(sum)
Now I don't seem to be able to get that in bash.
This is my code in bash
echo Enter a number:
read NUMBER
echo Enter a startpoint:
read STARTPOINT
echo Enter how many terms:
read TERMS
sum=0;
for ((n=0;n<$TERMS;n++));
do
STARTPOINT=$((STARTPOINT + NUMBER))
sum=$(($sum + $STARTPOINT))
echo $STARTPOINT
echo $sum
done
All the code is correct except the sum part, and because of it the code doesn't run properly. if I remove that part, it works fine. I just need to sum the outputs of the variable STARTPOINT.
Example
Input
NUMBER = 3 (means to increment 3 in the startpoint)
STARTPOINT = 2
TERMS = 5 (means to add 3 to 2 five times)
Expected output
5
8
11
14
17
And the part that I am having difficulty with is how to add all these numbers, when all added, it should print 55.
In this answer I changed your variable names to be lowercase. This is the conventional naming scheme in bash to avoid accidental name collisions with built-in variables and environment variables.
If I understood correctly, you want to build the following sequence and also sum it up:
startpoint + 1*number + startpoint + 2*number + ... + startpoint+ term*number
In that case you should not change startpoint inside your loop. Use another variable to store the result of startpoint + n*number.
startpoint=2 number=3 terms=5 sum=0
echo "$terms times increment $startpoint by $number:"
for ((n=1; n<=terms; n++));
do
((addend = startpoint + n*number))
echo "$addend"
((sum += addend))
done
echo "The sum is $sum"
However, instead of using a slow loop you could printing the sequence using seq and then calculate its sum using the closed formula for triangular numbers:
startpoint=2 number=3 terms=5
seq $((startpoint+number)) $number $((startpoint+terms*number))
((sum = terms*startpoint + terms*(terms+1)/2 * number))
echo "The sum is $sum"

How can I go on about getting the right output to the user in this recursive function in ruby?

def fibs_rec (n,barray = [])
return 1 if n == 1 || n == 0
a = fibs_rec(n-1,barray) + fibs_rec(n-2,barray)
barray << a
return a
end
for description, This function takes an argument n and prints the first n numbers in the fibonacci sequence but, it isnt quite working as it is supposed to be.
I want it to print the first n fibonacci numbers without any repetitions.
for example if n is 4, output should be 0,1,1,2 instead of 0,1,0,1,1,0,1,1,2. That basically happens when i print barray inside the recursion because i dont have any other option and for that sake i have removed that line.
The thing is I cant remove the return a and replace it with return barray. Not only will that mess up the functionality, fibs_rec is expecting to get a number back to perform the calculations and that wont work when I will return barray just to display the output to the user and neither can I print array because that will keep outputting the new data alongside with the old data and I just want it to be a one single clean output of the whole fibonacci numbers.
For the first question, you cannot remove return a and replace with return barray because
fibs_rec(n-1, barray) + fibs_rec(n-2, barray) will return an array instead of integer.
def fibs_rec(n, barray = [])
return 1 if n == 1 || n == 0
a = fibs_rec(n-1, barray) + fibs_rec(n-2, barray) # a = [2] + [2] wrong!
barray << a
return barray # return an array[]
end
Moreover, according to your problem description, it would be better not to write in a recursive program but if you are required to do a recursive program, I would suggest you that the fibs_rec function you wrote isn't trying to print the pattern but trying to find the fibo number at position n. For example:
# According to your program, you will miss the first 0 of fibonacci sequence
# (0,) 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
fibs_rec(0) # return: 1
fibs_rec(1) # return: 1
fibs_rec(2) # return: 2
fibs_rec(3) # return: 3
fibs_rec(4) # return: 5
. . .
If you want to print out the sequence using recursive function fibs_rec, you will need to create another function to call it from 0 to n.
There are a lot of good resources explaining about Fibonacci and recursive out there. You do not quite understand how recursive works. Try to understand it first. Good luck!

Generate first 10 numbers of a sequence

I have been trying to create this sequence:
2,7,17,37,67,...
I have to print first 10 numbers of the series.
To do this, I have created the following:
option explicit
Dim m,n,i,str,d
m=2
d=10
n=7
For i=0 to 10
n=n+d
d=d+10
str=str&n&vbcrlf
msgbox str
next
I am unable to print first two numbers, 2 and 7, as they are declared before the for loop. Even if I store them in a variable called str, they get printed after every execution. Is there a way to add these two and print them only once.
You could add your initial value of m to your string before you start running your sequence. Then, append the value of n to your string at the start of your loop instead of the end so that you capture n's initial value. For example:
m=2: d=10: n=7
str = m & vbCrLf ' Capture initial value of m
For i = 1 to 9
str = str & n & vbCrLf ' Capture initial value of n
n = n + d
d = d + 10
Next
MsgBox str
Note that you're only looping 9 times now, since you've already captured the first number in your sequence (m) prior to your loop.
I also moved MsgBox outside your loop so that it only appears once, after the full 10-number sequence has been generated.

Need to calculate standard deviation from an array using bash and awk?

Guys I'm new to awk and I'm struggling with awk command to find the standard deviation.
I have got the mean using the following:
echo ${GfieldList[#]} | awk 'NF {sum=0;for (i=1;i<=NF;i++)sum+=$i; print "Mean= " sum / NF; }'
Standard Deviation formula is:
sqrt((1/N)*(sum of (value - mean)^2))
I have found the mean using the above formula
Can you guys help me with the awk command for this one?
An alternate formula for the standard deviation is the square root of the quantity: (the mean square minus the square of the mean). This is used below:
$ echo 20 21 22 | awk 'NF {sum=0;ssq=0;for (i=1;i<=NF;i++){sum+=$i;ssq+=$i**2}; print "Std Dev=" (ssq/NF-(sum/NF)**2)**0.5}'
Std Dev=0.816497
Notes:
In awk, NF is the number of "fields" on a line. In our case, every field is a number, so NF is the number of numbers on a given line.
ssq is the sum of the squares of each number on the line. Thus, ssq/NF is the mean square.
sum is the sum of the numbers on the line. Thus sum/NF is the mean and (sum/NF)**2 is the square of the mean.
As per the formular, then, the standard deviation is (ssq/NF-(sum/NF)**2)**0.5.
The awk code
NF
This serves as a condition: the statements which follow will only be executed if the number of fields on this line, NF, evaluates to true, meaning non-zero. In other words, this condition will cause empty lines to be skipped.
sum=0;ssq=0;
This initializes sum and ssq to zero. This is only needed if there is more than one line of input.
for (i=1;i<=NF;i++){sum+=$i;ssq+=$i**2}
This puts the sum of all the numbers in sum and the sum of the square of the numbers in ssq.
print "Std Dev=" (ssq/NF-(sum/NF)**2)**0.5
This prints out the standard deviation.
Once you know the mean:
awk '{
for (i = 1;i <= NF; i++) {
sum += $i
};
print sum / NF
}' # for 2, 4, 4, 4, 5, 5, 7, 9 gives 5
then the standard deviation can be found thus:
awk -vM=5 '{
for (i = 1; i <= NF; i++) {
sum += ($i-M) * ($i-M)
};
print sqrt (sum / NF)
}' # for 2, 4, 4, 4, 5, 5, 7, 9 gives 2
In "compressed" form:
awk '{for(i=1;i<=NF;i++){sum+=$i};print sum/NF}'
awk -vM=5 '{for(i=1;i<=NF;i++){sum+=($i-M)*($i-M)};print sqrt(sum/NF)}'
(changing the value for M to the actual mean extracted from the first command).

Sorting in Lua, counting number of items

Two quick questions (I hope...) with the following code. The script below checks if a number is prime, and if not, returns all the factors for that number, otherwise it just returns that the number prime. Pay no attention to the zs. stuff in the script, for that is client specific and has no bearing on script functionality.
The script itself works almost wonderfully, except for two minor details - the first being the factor list doesn't return itself sorted... that is, for 24, it'd return 1, 2, 12, 3, 8, 4, 6, and 24 instead of 1, 2, 3, 4, 6, 8, 12, and 24. I can't print it as a table, so it does need to be returned as a list. If it has to be sorted as a table first THEN turned into a list, I can deal with that. All that matters is the end result being the list.
The other detail is that I need to check if there are only two numbers in the list or more. If there are only two numbers, it's a prime (1 and the number). The current way I have it does not work. Is there a way to accomplish this? I appreciate all the help!
function get_all_factors(number)
local factors = 1
for possible_factor=2, math.sqrt(number), 1 do
local remainder = number%possible_factor
if remainder == 0 then
local factor, factor_pair = possible_factor, number/possible_factor
factors = factors .. ", " .. factor
if factor ~= factor_pair then
factors = factors .. ", " .. factor_pair
end
end
end
factors = factors .. ", and " .. number
return factors
end
local allfactors = get_all_factors(zs.param(1))
if zs.func.numitems(allfactors)==2 then
return zs.param(1) .. " is prime."
else
return zs.param(1) .. " is not prime, and its factors are: " .. allfactors
end
If I understood your problem correctly I recommend splitting up your logic a bit. The idea would be first to create a table containing the fractions and then doing the sort and after that creating the string representation.
-- Creates a table containing all the factors for a number.
function createFactors(n)
local factors = {}
-- The for loop etc. would be here. If you find a factor then add
-- it in the table.
-- ...
table.insert(factors, n)
-- ...
--# Once you've found all the factors just return the table.
return factors
end
-- Lua offers a method for sorting tables called table.sort.
local factors = createFactors(139)
table.sort(factors)
-- There is a method for creating a string representation of a table
-- called table.concat, the first parameter is the table and the second
-- is the character that is used to delimit the values.
table.concat(factors, ", ")
Nice ansewr from ponzao. To put the finishing touches on your result, here's a general-purpose routine for turning a list of strings in Lua into an English string, with "and", that represents the list:
function string.commafy(t, andword)
andword = andword or 'and'
local n = #t
if n == 1 then
return t[1]
elseif n == 2 then
return table.concat { t[1], ' ', andword, ' ', t[2] }
else
local last = t[n]
t[n] = andword .. ' ' .. t[n]
local answer = table.concat(t, ', ')
t[n] = last
return answer
end
end
Instead of table.concat(factors, ', ') use string.commafy(factors).

Resources