Rails Average - Discount 0 values - ruby-on-rails

I create arrays which I need to find the averages of as follows:
total_rating = []
#add numbers to total_rating
average = total_rating.inject(:+).to_f / total_rating.size
How can I remove values of 0 from this average calculation? I dont want the 0 row to be computed in the average calculation.

total_rating.reject(&:zero?)

Related

why am I getting a value greater than 1 as dice score

I have two segmented images, and I've computed the dice score using the formula below, however, I keep getting values greater than 1 (like 11.8, 12.8) as a dice score. is there a reason why? or is my approach for computing the dice score wrong?
def dice(X, Y):
intersection = (X * Y).sum()
union = X.sum() + Y.sum()
return ((2. * intersection) / (union))

How can I obtain this specific series data to calculate time-to-funding-weighted average of premium index?

I'm looking to calculate and plot the funding rate of Binance BTCUSDT Perpetual and have come across the following documentation page: https://www.binance.com/en/support/faq/360033525031
It states:
The Funding Rate formula:
"Funding Rate (F) = Average Premium Index (P) + clamp (interest rate - Premium Index (P), 0.05%, -0.05%)"
I'm obtaining the "Premium Index" just fine, just with "p = request.security("BINANCE:BTCUSDT_PREMIUM", "", close)*100"
However I'm currently struggling with how to obtain the:
"Time-to-funding weighted Average of Premium Index " which apparently is calculated with
"Average Premium Index (P) = (1 * Premium_Index_1 + 2 * Premium_Index_2 + 3 * Premium_Index_3 +···+·480 * Premium_index_480)/(1+2+3+···+480)"
(the funding period for Binance is 8 hours hence the average over 480 minutes)
My exact question is, how do I backtrack to the last funding timestamp of 00:00 / 08:00 / 16:00, then obtain an array / series data of the premium index at each of the last 480 minutes, so that I can then iterate over it to use the above formula for the time weighted average?
Thank you very much for any advice in advance. My apologies if the answer is obvious I'm very new to Pine Script.
I believe you can obtain the time weighted average premium like so:
premium = request.security("BINANCE:BTCUSDT_PREMIUM", "1", close)
new_funding_period = ta.change(time("480")) != 0
var int n = na
var float premium_sum = na
var int n_sum = na
if new_funding_period
n := 1
premium_sum := premium
n_sum := 1
else
n += 1
premium_sum += premium * n
n_sum += n
predicted_TWAP = premium_sum / n_sum
current_TWAP = ta.valuewhen(new_funding_period, predicted_TWAP[1], 0)
However, you are limited to performing the calculation on a 1 minute chart to obtain accurate results due to being unable to reliably retrieve the values from a security call from a lower timeframe when the chart is set to a higher timeframe than 1 minute.

Lua multiple inputs in table

I'm new to lua and I have this assignment and one of the questions I'm really stumped on is asking:
"A program that asks the user repeatedly for students' scores, will stop when the user enters a score of 999 then the program should calculate and display the number of scores entered, highest score, lowest score, and the average score. Make sure to display an error message if a score less than zero or more than 100 is entered by user. "
I've been at this all week long and still can't figure out what to do and its due at 11:59pm est. Any insight and direction would be great.
-How do I input multiple values in a growing table scores = {}? Where the size is given by the number of inputs for variable s after the user enters 999 and ends the repeat loop. This is actually my BIGGEST problem.
My Code:
local scores = {}, avg
repeat
io.write("Enter score(s)")
local s = tonumber(io.read()) --input and convert data type
print(s, type(s)) --s value, check input type
if(s < 0 or s > 100) then
print("Error.")
end
until (s == 999)
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end
-- -----------------------------------------------------------Attemps to find a way to put s values in scores table-----------------------------------------------------------------------------------------
--[[scores[#scores+1] = s ----Attempt 1
print (scores)
for i = 0, #s, 1 do ----Attempt 2
scores{s} = s[i]
print (i, scores) --tried a multitude of different ways and
--kept getting the same number printed once or memory location of last entered number
end
for i, s in ipairs (scores) do --Attempt 3
print (i, s)
end
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end --]]
-- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[function average(myTable)
local sum = 0
for i in scores do
sum = sum + i
end
return (sum / #scores)
end
print ("The number of values in the table"..#scores)
print ("The average of the scores is "..average(s))
print ("The max value in the table is "..math.max(s))
print ("The minimum value in the table is "..math.min(s))
table.maxn(scores), table.minn(scores)
--]]
io.write("Please press enter to continue")
io.read()

How to normalize Pearson Correlation between 0 and 1?

I came across the formula for the Pearson Correlation but it gives values between -1 and 1. How would I modify the formula so that it gives values between 0 and 1?
To normalize any set of numbers to be between 0 and 1, subtract the minimum and divide by the range.
In your case the min is -1 and the range is 2, so if a value in your set is -0.5, that value becomes:
(-0.5 - (-1)) / 2
= 0.25

How do I create an average for a temperature data set?

I am writing a program which takes a set of data and then averages it. This data set is the average temperature at Laguardia Airport for every month which corresponds with a temperature.
Here is an example one data point:
2009-07,23.6
Which is year-month, temp.
I have 163 data points. All of the data points are in a .txt file, each on a new line.
I made the data into an array and split it. For some reason, my program says my average is 0 every time I try to run it
Here is my code:
data = File.open("avg_temp.txt", "r+")
contents = data.read
contents = contents.split("\r\n")
contents.collect! do |x|
x.split(',')
end
sum = 0
data.each do |x|
sum = sum + x[1].to_f
end
avg = sum / contents.length
puts avg
assign avg = sum/contents.length outside the loop after the end. Variables defined within a loop have a scope limited to that loop. Also you are looping over data, should be content
contents.each do |x|
puts x[1] # to check if the right value is being evaluated
sum = sum + x[1].to_f
end
avg = sum/contents.length
Your avg is not the top level local variable. Thus you can't access it from the top level. avg is scoped to the block only. You can do below :-
avg = 0
data.each do |x|
sum = sum + temp[1].to_f
avg = sum / contents.length
end
puts avg
sum = 0
data.each do |x|
sum = sum + temp[1].to_f
avg = sum / contents.length
end
puts avg
The avg variable is no longer in scope, as it's outside of the each block. To print the avg, simply move it inside of the block like so
sum = 0
data.each do |x|
sum = sum + temp[1].to_f
avg = sum / contents.length
puts avg
end
Or move the avg variable outside of the loop (to perform the action once, after your loop has exited)
sum = 0
data.each do |x|
sum = sum + temp[1].to_f
end
avg = sum / contents.length
puts avg
More info at http://rubyflare.com/2009/09/30/variables-scope-and-iterators/
I'd write this more simply:
lines = 0
sum = 0
File.foreach("avg_temp.txt") do |data|
sum += data.split(',').last.to_f
lines = $.
end
puts 'Average: %f over %d datapoints' % [sum / lines.to_i, lines]
# >> Average: 23.375000 over 4 datapoints
Which outputs:
Average: 23.375000 over 4 datapoints
Starting with "avg_temp.txt" looking like:
2009-07,23.6
2009-08,23.7
2009-09,23.6
2009-10,22.6
To 'splain it:
$. is the current line number. Each time through the loop it reassigns the last read line-number to lines so we know how many to divide by.
foreach reads line-by-line, so there's no need to split the file. That also explains why I use $. to keep track of the number of elements. It also means this could read a file containing millions or billions of values without a problem, where read would go to its knees.

Resources